<?php

/**
 * 列队任务
 */
include_once dirname(dirname(__FILE__)) . '/nn_db.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/op/op_queue.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/vod_audit/vod_audit.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/vod_audit/vod_index_media.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/vod_audit/vod_audit_word.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_cms_manager/contentframe/vod_audit/nncms_vod_audit_notify_action.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/asset_online/asset_online.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/sp/sp.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/cp/cp.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/pass_queue/pass_queue.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/message/nl_message.class.php';

class queue_task_model
{

    private $op_queue;

    private $db;

    public $op_sp = null;
    public $sp_config = null;
    public $sp_config_encode_url = null;
    public $dc = null;
    public $int_weight = 0;
    public $is_group = 0;
    public $error_info = null;
    public $arr_cp_config = null;

    public $is_need_notify_data = false;
    public $arr_nedd_notify_data = null;

    public function __construct($dc = null, $sp_id = null, $sp_config = null)
    {
        $this->dc = $dc;
        $this->op_queue = new op_queue($this);
        $this->db = nn_get_db(NL_DB_WRITE);
        $this->db->open();
        $this->sp_config = $sp_config;
        $this->op_sp = $sp_id;
        $this->error_info = null;
    }

    /**
     * 权重设置
     * @param $int_weight
     */
    public function _set_weight($int_weight)
    {
        $int_weight = (int)$int_weight;
        $this->int_weight = $int_weight > 0 ? $int_weight : 0;
    }

    /**
     * 获取权重
     */
    public function _get_weight()
    {
        $int_weight = (int)$this->int_weight;
        return $int_weight > 0 ? $int_weight : 0;
    }

    /**
     * 设置消息中的内容是否为分组消息
     * @param $int_weight
     */
    public function _set_is_group($is_group)
    {
        $is_group = (int)$is_group;
        $this->is_group = $is_group > 0 ? $is_group : 0;
    }

    /**
     * 获取消息中内容是否分组消息
     * @return int
     */
    public function _get_is_group()
    {
        $is_group = (int)$this->is_group;
        return $is_group > 0 ? $is_group : 0;
    }


    /**
     * @查询执行的任务有多少
     */


    public function get_current_task_num($sp_id, $video_type)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $sql = "select * from nns_mgtvbk_sp where nns_id='" . $sp_id . "'";
        $sp_config = nl_db_get_one($sql, $db);
        $sp_config = json_decode($sp_config['nns_config'], true);

        //当前总任务
        $count_all = nl_db_get_col("select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='$video_type'", $db);

        //当前失败的任务
        if(isset($sp_config['cdn_media_playurl_by_csv']) && $sp_config['cdn_media_playurl_by_csv'] == '1' && $video_type == 'media')
		{
            $count_fial = nl_db_get_col("select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='$video_type' and (nns_status in (-1,7,6,11)  or nns_epg_status=100)", $db);
		}
		else
		{
		    $count_fial = nl_db_get_col("select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='$video_type' and (nns_status in (-1,7,11)  or nns_epg_status=100)", $db);
		}
        $count_finish = 0;


        $action_ary = array(
            BK_OP_ADD => $video_type . '_' . BK_OP_ADD,
            BK_OP_MODIFY => $video_type . '_' . BK_OP_MODIFY,
            BK_OP_DELETE => $video_type . '_' . BK_OP_DELETE,
        );
        $where_array = array();
        //
        foreach ($action_ary as $key => $val)
        {
            //print_r($config);
            //$config[$val];
            $config = $sp_config[$val];
            //判断当前操作(添加、删除、修改)的最终状态---0为注入CDN和EPG，1为注入CDN，2为注入EPG
            if ($config['status'] == 0)
            {
                $where_array[] = "(nns_status = 0 and nns_epg_status = 99 and nns_action='" . $key . "')";
            } //优先执行注入---0或不设为优先执行CDN注入，再执行EPG注入，1为优先执行EPG注入，再执行CDN注入
            elseif ($config['status'] == 1 && $config['priority'] == 0)
            {
                $where_array[] = "(nns_status = 0 and nns_action='" . $key . "')";
            } elseif ($config['status'] == 2 && $config['priority'] == 1)
            {
                $where_array[] = "(nns_epg_status = 99 and nns_action='" . $key . "')";
            }
        }


        $sql = "select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='$video_type' ";
        if (is_array(array_filter($where_array)) && count(array_filter($where_array)) > 0)
        {
            $sql .= " and (" . implode(array_filter($where_array), " or ") . ") ";
        } else
        {
            return null;
        }
        echo "<hr>";
        echo "{$sql}";
        echo "<hr>";

        //执行成功的c2任务数
        $count_finish = nl_db_get_col($sql, $db);
        //正在执行的c2任务数
        $count_do = $count_all - $count_fial - $count_finish;
        if ($count_do < 1)
        {
            $count_do = 0;
        }
        return $count_do;
    }


    /**
     * @重队列中获取任务
     * @param $sp_id string
     * @param $num  int
     */


    public function q_get_task($sp_id, $num = 2)
    {
        //include_once 'sp_model.php';
        set_time_limit(0);
// 		$db = nn_get_db(NL_DB_WRITE);
// 		$db->open();

        $dc = nl_get_dc(array(
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $db = $dc->db();

        np_runtime_ex('get_task', false);
        //根据规则，从nns_mgtvbk_op_queue表中获取nns_status状态为（0,6,7）的任务
        $re = $this->op_queue->get_task($db, $sp_id, $num);
        $run_time = ' RunTime:' . np_runtime_ex('get_task', true);
        echo $run_time . PHP_EOL;
        i_write_log_core(var_export($re, true), 'get_task/' . $sp_id);
        $sql = "select * from nns_mgtvbk_sp where nns_id='" . $sp_id . "'";
        $sp_conf = nl_db_get_one($sql, $db);
        $sp_conf = json_decode($sp_conf['nns_config'], true);
//		var_dump($sp_conf);die;
        i_write_log_core(var_export($sp_conf, true), 'get_task_config/' . $sp_id);
        //中心同步指令暂停下发【0:开启；1:关闭】
        if (isset($sp_conf['close_queue']) && (int)$sp_conf['close_queue'] === 1)
        {
            //unset($db);
            return false;
        }
        $temp_result_cp_info = null;
        if ($re['state'] == 100)
        {
            $tasks = $re['data'];
            //入c2_task库
            if (is_array($tasks) && count($tasks) > 0)
            {
                //查询当前正在执行的有多少记录
                /*$str="";
				if($sp_id=='yntt'||$sp_id=='ynyd'||$sp_id=='dxjd' || $sp_id=='sdlt'){
					$str = "and nns_epg_status=97";
				}elseif($sp_id=='sihua'){
					$str = "and nns_status in (1,5) and nns_epg_status=97";
				}elseif($sp_id=='shanghai_mobile'){
					$str = "and nns_status in (1,5,6,8)";
				}else{
					$str = "and nns_epg_status=97 and nns_status in (0,1,5)  ";
				}
				$sql_video_cont = "select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='video'   $str";
				*/

                //$num_video = nl_db_get_col($sql_video_cont, $db);
                //当前正在执行的任务数(类型为主媒资)
                $num_video = $this->get_current_task_num($sp_id, 'video');
                //获取CDN注入主媒资队列上限
                $num_video_set = strlen($sp_conf['cdn_video_max']) > 0 ? (int)$sp_conf['cdn_video_max'] : 100;

                //$sql_index_cont = "select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='index'   $str";
                //$num_index = nl_db_get_col($sql_index_cont, $db);
                //当前正在执行的任务数(类型为分集)
                $num_index = $this->get_current_task_num($sp_id, 'index');
                //获取CDN注入分集队列上限
                $num_index_set = strlen($sp_conf['cdn_index_max']) > 0 ? (int)$sp_conf['cdn_index_max'] : 100;

                //$sql_media_cont = "select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='media'   $str";
                //$num_media = nl_db_get_col($sql_media_cont, $db);
                //当前正在执行的任务数(类型为片源)
                $num_media = $this->get_current_task_num($sp_id, 'media');
                //获取CDN注入片源队列上限
                $num_media_set = strlen($sp_conf['cdn_media_max']) > 0 ? (int)$sp_conf['cdn_media_max'] : 100;
                //遍历从nns_mgtvbk_op_queue中取出的任务
                $temp_num = 0;

                if (isset($sp_conf['create_media_mode']) && $sp_conf['create_media_mode'] == '1' && isset($sp_conf['media_service_type']) && strlen($sp_conf['media_service_type']) > 0)
                {
                    include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/vod_media/vod_media.class.php';
                    include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/op_queue/op_queue.class.php';
                }
                foreach ($tasks as $task_info)
                {

                    $task_info['nns_ex_data'] = json_decode($task_info['nns_ex_data'], true);

                    $int_nns_is_group = isset($task_info['nns_is_group']) ? $task_info['nns_is_group'] : 0;
                    $int_nns_weight = isset($task_info['nns_weight']) ? $task_info['nns_weight'] : 0;
                    $str_c2_nns_cp_id = isset($task_info['nns_cp_id']) ? $task_info['nns_cp_id'] : '';

                    np_runtime_ex('task' . $task_info['nns_id'], false);
                    $temp_num++;
                    echo "<hr/>";
                    echo "第[{$temp_num}]次循环<br/>";
                    //当前正在执行的任务数
                    echo $num_video . "----video<br/>";
                    echo $num_index . "----index<br/>";
                    echo $num_media . "----media<br/>";
                    if ($task_info['nns_type'] == 'video')
                    {
                        //获取op_queue任务名称
                        $task_arr = $this->get_task_name($task_info['nns_video_id'], $task_info['nns_type']);
                        //如果当前正在执行的c2任务数(主媒资)>=CDN注入主媒资队列上限
                        if ($num_video >= $num_video_set)
                        {
                            echo '1--video';
                            echo "<br/>";

// 							break;
                            continue;
                        }
                    }
                    elseif ($task_info['nns_type'] == 'index')
                    {
                        //获取op_queue任务名称
                        $task_arr = $this->get_task_name($task_info['nns_index_id'], $task_info['nns_type']);
                        //如果当前正在执行的c2任务数(分集)>=CDN注入分集队列上限
                        if ($num_index >= $num_index_set)
                        {
                            echo '1--index';
                            echo "<br/>";
// 							break;
                            continue;
                        }
                    }
                    elseif ($task_info['nns_type'] == 'media')
                    {
                        //获取op_queue任务名称
                        $task_arr = $this->get_task_name($task_info['nns_media_id'], $task_info['nns_type']);

                        if (isset($task_arr['nns_media_encode_flag']) && $task_arr['nns_media_encode_flag'] != 0 && strlen($task_arr['cp_id']) > 0)
                        {
                            if (!isset($temp_result_cp_info[$task_arr['cp_id']]))
                            {
                                $result_cp_info = nl_cp::query_by_id_by_db($db, $task_arr['cp_id']);
                                $result_cp_info = (isset($result_cp_info['data_info']['nns_config']) && strlen($result_cp_info['data_info']['nns_config']) > 0) ? json_decode($result_cp_info['data_info']['nns_config'], true) : null;
                                $temp_result_cp_info[$task_arr['cp_id']] = $result_cp_info;
                            } else
                            {
                                $result_cp_info = $temp_result_cp_info[$task_arr['cp_id']];
                            }
                        }
                        if (isset($sp_conf['create_media_mode']) && $sp_conf['create_media_mode'] == '1' && isset($sp_conf['media_service_type'])
                            && strlen($sp_conf['media_service_type']) > 0 && (isset($task_arr['nns_media_encode_flag']) && in_array($task_arr['nns_media_encode_flag'], array('0', '1'))))
                        {
                            $result_temp_media = nl_vod_media_v2::query_by_id($dc, $task_info['nns_media_id']);
                            if ($result_temp_media['ret'] != 0 || !isset($result_temp_media['data_info']) || !is_array($result_temp_media['data_info']) || empty($result_temp_media['data_info']))
                            {
                                echo "<font color='red'>查询片源数据库执行失败:</font><br>";
                                var_dump($result_temp_media);
                                continue;
                            }
                            $result_temp_media = $result_temp_media['data_info'];
                            unset($result_temp_media['nns_integer_id']);
                            $temp_message_id = '';
                            if (isset($sp_conf['fuse_platform_mark']) && strlen($sp_conf['fuse_platform_mark']) > 0)
                            {
                                $result_media_org_media = nl_vod_media_v2::query_media_org_exsist($dc, $result_temp_media['nns_import_id'], substr($result_temp_media['nns_cp_id'], 5), $result_temp_media['nns_import_source']);
                                if ($result_media_org_media['ret'] != 0)
                                {
                                    echo "<font color='red'>配置了融合平台数据但是数据库查询失败:</font><br>";
                                    var_dump($result_media_org_media);
                                    continue;
                                }
                                if (!isset($result_media_org_media['data_info']) || !is_array($result_media_org_media['data_info']) || empty($result_media_org_media['data_info']))
                                {
                                    echo "<font color='red'>配置了融合平台数据,查询数据成功，但是没数据:</font><br>";
                                    var_dump($result_media_org_media, $task_info['nns_id']);
                                    nl_op_queue::edit($dc, array('nns_state' => 1), $task_info['nns_id']);
                                    continue;
                                }
                                $result_c2_task_data = nl_c2_task::query_c2_exsist($dc, 'media', $result_media_org_media['data_info']['nns_id'], $sp_conf['fuse_platform_mark']);
                                if ($result_c2_task_data['ret'] != 0)
                                {
                                    echo "<font color='red'>配置了融合平台数据,查询C2数据库执行失败:</font><br>";
                                    var_dump($result_c2_task_data);
                                    continue;
                                }
                                if (!isset($result_c2_task_data['data_info'][0]) || !is_array($result_c2_task_data['data_info'][0]) || empty($result_c2_task_data['data_info'][0]))
                                {
                                    echo "<font color='red'>配置了融合平台数据,查询C2数据库,查询数据成功，但是没数据:</font><br>";
                                    var_dump($result_c2_task_data);
                                    continue;
                                } else
                                {
                                    $temp_message_id = (isset($result_c2_task_data['data_info'][0]['nns_message_id']) && strlen($result_c2_task_data['data_info'][0]['nns_message_id']) > 0) ? $result_c2_task_data['data_info'][0]['nns_message_id'] : '';
                                }
                            }
                            $result_temp_media['nns_id'] = np_guid_rand();
                            $result_temp_media['nns_encode_flag'] = '2';
                            $result_temp_media['nns_import_id'] = $result_temp_media['nns_import_id'] . '_' . $sp_id;
                            $result_temp_media['nns_media_service'] = $sp_conf['media_service_type'];
                            $result_media_exsist = nl_vod_media_v2::query_media_exsist($dc, $result_temp_media['nns_import_id'], $result_temp_media['nns_cp_id'], $result_temp_media['nns_import_source'], $sp_conf['media_service_type']);
                            if ($result_media_exsist['ret'] != 0)
                            {
                                echo "<font color='red'>查询片源是否存在数据库失败:</font><br>";
                                var_dump($result_media_exsist);
                                continue;
                            }
                            if (!isset($result_media_exsist['data_info']) || !is_array($result_media_exsist['data_info']) || empty($result_media_exsist['data_info']))
                            {
                                $result_vod_media_add = nl_vod_media_v2::add($dc, $result_temp_media);
                                if ($result_vod_media_add['ret'] != 0)
                                {
                                    echo "<font color='red'>片源添加失败:</font><br>";
                                    var_dump($result_vod_media_add);
                                    continue;
                                }
                            } else
                            {
                                $result_temp_media['nns_id'] = $result_media_exsist['data_info']['nns_id'];
                                $result_vod_media_edit = nl_vod_media_v2::edit($dc, array('nns_media_service' => $result_temp_media['nns_media_service']), $result_temp_media['nns_id']);
                                if ($result_vod_media_edit['ret'] != 0)
                                {
                                    echo "<font color='red'>片源修改失败:</font><br>";
                                    var_dump($result_vod_media_edit);
                                    continue;
                                }
                            }
                            $temp_op_queue_data = $task_info;
                            $temp_op_queue_data['nns_ex_data'] = is_array($temp_op_queue_data['nns_ex_data']) ? json_encode($temp_op_queue_data['nns_ex_data']) : '';
                            $temp_op_queue_data['nns_media_id'] = $result_temp_media['nns_id'];
                            $temp_op_queue_data['nns_name'] = $temp_op_queue_data['nns_name'] . " [{$sp_conf['media_service_type']}]";
                            $temp_op_queue_data['nns_id'] = np_guid_rand();
                            if (strlen($temp_message_id) > 0)
                            {
                                $temp_op_queue_data['nns_message_id'] = $temp_message_id;
                            }
                            $result_op_queue_add = nl_op_queue::add($dc, $temp_op_queue_data);
                            if ($result_op_queue_add['ret'] != 0)
                            {
                                echo "<font color='red'>OP queue 队列添加失败:</font><br>";
                                var_dump($result_op_queue_add);
                                continue;
                            }
                            $result_op_queue_del = nl_op_queue::delete_op_queue($dc, array($task_info['nns_id']));
                            if ($result_op_queue_del['ret'] != 0)
                            {
                                echo "<font color='red'>OP queue 队列删除失败:</font><br>";
                                var_dump($result_op_queue_del);
                                continue;
                            }
                            continue;
                        }
                        //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                        if ($num_media >= $num_media_set)
                        {
                            echo '1--media';
                            echo "<br/>";
// 							break;
                            continue;
                        }
                    }
                    elseif ($task_info['nns_type'] == 'live_media')
                    {
                        //获取op_queue任务名称
                        $task_arr = $this->get_task_name($task_info['nns_media_id'], $task_info['nns_type']);
                        //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
// 					    if($num_media>=$num_media_set){
// 					        echo '1--media';echo "<br/>";
                        // 							break;
// 					        continue;
// 					    }
                    }
                    elseif ($task_info['nns_type'] == 'live')
                    {
                        //获取op_queue任务名称
                        $task_arr = $this->get_task_name($task_info['nns_video_id'], $task_info['nns_type']);
                        //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                        // 					    if($num_media>=$num_media_set){
                        // 					        echo '1--media';echo "<br/>";
                        // 							break;
                        // 					        continue;
                        // 					    }
                    }
                    elseif ($task_info['nns_type'] == 'playbill')
                    {
                        //获取op_queue任务名称
                        $task_arr = $this->get_task_name($task_info['nns_media_id'], $task_info['nns_type']);
                        //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                        // 					    if($num_media>=$num_media_set){
                        // 					        echo '1--media';echo "<br/>";
                        // 							break;
                        // 					        continue;
                        // 					    }
                    }
                    elseif ($task_info['nns_type'] == 'file')
                    {
                        //获取op_queue任务名称
                        $task_arr = $this->get_task_name($task_info['nns_video_id'], $task_info['nns_type']);
                        //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                        // 					    if($num_media>=$num_media_set){
                        // 					        echo '1--media';echo "<br/>";
                        // 							break;
                        // 					        continue;
                        // 					    }
                    }
                    elseif ($task_info['nns_type'] == 'product')
                    {
                        //获取op_queue任务名称
                        $task_arr = $this->get_task_name($task_info['nns_video_id'], $task_info['nns_type']);
                        //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                        // 					    if($num_media>=$num_media_set){
                        // 					        echo '1--media';echo "<br/>";
                        // 							break;
                        // 					        continue;
                        // 					    }
                    }
                    $task_info['nns_name'] = ($task_info['nns_type'] == 'media' && isset($task_arr['nns_media_encode_flag']) && $task_arr['nns_media_encode_flag'] != 0) ? $task_info['nns_name'] : $task_arr['task_name'];
                    //如果是主媒资并且不是删除操作，则将数据写入nns_mgtvbk_category_content表中
                    if ($task_info['nns_type'] == BK_OP_VIDEO && $task_info['nns_action'] != BK_OP_DELETE)
                    {
                        //主媒资信息
                        $vod_info = video_model::get_vod_info($task_info['nns_video_id']);
                        $asset_categori_id = $vod_info['nns_category_id'];//资源库栏目ID
                        $sp_category = sp_category_model::get_bind_sp_category($sp_id, $asset_categori_id);
                        if (is_array($sp_category))
                        {
                            foreach ($sp_category as $category)
                            {
                                $data = array(
                                    'nns_id' => np_guid_rand($sp_id),
                                    'nns_org_id' => $sp_id,
                                    'nns_category_id' => $category['nns_id'],
                                    'nns_category_name' => $category['nns_name'],
                                    'nns_video_id' => $task_info['nns_video_id'],
                                    'nns_video_name' => $vod_info['nns_name'],
                                    'nns_create_time' => date('Y-m-d H:i:s'),
                                    'nns_pinyin' => $vod_info['nns_pinyin'],
                                    'nns_video_type' => 0,
                                    'nns_status' => 0,
                                );
                                @nl_db_insert($db, 'nns_mgtvbk_category_content', $data);
                            }
                        }
                    }
                    $nns_ref_id = "";
                    $nns_parent_id = "";

                    //查询任务信息
                    switch ($task_info['nns_type'])
                    {
                        case BK_OP_VIDEO:
                            $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_video_id']}'";
                            //nns_ref_id为nns_vod表的guid;
                            $nns_ref_id = $task_info['nns_video_id'];
                            $nns_parent_id = 0;
                            break;
                        case BK_OP_INDEX:
                            $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_index_id']}'";
                            //nns_ref_id为nns_vod_index表的guid;
                            $nns_ref_id = $task_info['nns_index_id'];
                            //nns_src_id为nns_vod表的guid
                            $nns_parent_id = $task_info['nns_video_id'];
                            break;
                        case BK_OP_MEDIA:
                            $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_media_id']}'";
                            //nns_ref_id为nns_vod_media表的guid;
                            $nns_ref_id = $task_info['nns_media_id'];
                            //nns_src_id为nns_vod_index表的guid
                            $nns_parent_id = $task_info['nns_index_id'];
                            break;
                        case BK_OP_LIVE:
                            $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_video_id']}'";
                            //nns_ref_id为nns_vod_media表的guid;
                            $nns_ref_id = $task_info['nns_video_id'];
                            //nns_src_id为nns_vod_index表的guid
                            $nns_parent_id = 0;
                            break;
                        case BK_OP_LIVE_MEDIA:
                            $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_media_id']}'";
                            //nns_ref_id为nns_vod_media表的guid;
                            $nns_ref_id = $task_info['nns_media_id'];
                            //nns_src_id为nns_vod_index表的guid
                            $nns_parent_id = $task_info['nns_index_id'];
                            break;
                        case BK_OP_PLAYBILL:
                            $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_media_id']}'";
                            //nns_ref_id为nns_vod_media表的guid;
                            $nns_ref_id = $task_info['nns_media_id'];
                            //nns_src_id为nns_vod_index表的guid
                            $nns_parent_id = $task_info['nns_index_id'];
                            break;
                        case BK_OP_FILE:
                            $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_video_id']}'";
                            //nns_ref_id为nns_vod_media表的guid;
                            $nns_ref_id = $task_info['nns_video_id'];
                            //nns_src_id为nns_vod_index表的guid
                            $nns_parent_id = 0;
                            break;
                        case BK_OP_PRODUCT:
                            $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_video_id']}'";
                            //nns_ref_id为nns_vod_media表的guid;
                            $nns_ref_id = $task_info['nns_video_id'];
                            //nns_src_id为nns_vod_index表的guid
                            $nns_parent_id = 0;
                            break;
                    }
                    //查询当前任务是否在C2任务表中
                    $c2_task_info = nl_db_get_one($sql, $db);
// 					if($sp_id == 'starcor_cdn' && is_array($c2_task_info) && !empty($c2_task_info))
// 					{
// 					    nl_execute_by_db("delete from nns_mgtvbk_op_queue where nns_id='{$task_info['nns_id']}' and nns_org_id='{$sp_id}' ", $db);
// 					    continue;
// 					}
                    //查询C2表中当前操作是否为最终状态，如果不是最终状态就不用执行
                    $sp_config = sp_model::get_sp_config($c2_task_info['nns_org_id'], $c2_task_info['nns_type'] . '_' . $c2_task_info['nns_action']);
                    $q_report_task = $this->is_succ_state($sp_config, $c2_task_info);
                    //如果同等片源下的删除	放过 cdn_import_media_sort同分集片源注入排序方式【0或则不设置按照列队排序，1先添加再删除，保证EPG无缝注入】
                    if (isset($sp_conf['cdn_import_media_sort']) && (int)$sp_conf['cdn_import_media_sort'] === 1 && $task_info['nns_type'] == BK_OP_MEDIA && $task_info['nns_action'] == BK_OP_DELETE)
                    {
                        //该分集下是否有片源不为删除状态，并还未执行完毕
                        $is_index_in_media = $this->op_queue->get_index_status($db, $sp_id, $task_info['nns_index_id'], $task_info['nns_media_id']);
                        if ($is_index_in_media > 0)
                        {
                            //新增同等片源下，如果C2中无同一片源的新增，则删除此删除队列
                            if (empty($c2_task_info) || $c2_task_info === false)
                            {
                                echo 'c2 is empty task';
                                echo "<br/>";
                            } else
                            {
                                echo 'have media add cdn ,this action continue';
                                echo "<br/>";
                                continue;
                            }
                        }
                    }
                    //如果片源的操作是注入失败的，那么就默认这个操作已经完成
                    // if(is_array($c2_task_info)&&$c2_task_info!=null){
                    // if($c2_task_info['nns_type']==BK_OP_MEDIA&&$c2_task_info['nns_status']==-1&&$c2_task_info['nns_type']==BK_OP_MEDIA){
                    // if($task_info['nns_id']!=$c2_task_info['nns_op_id']){
                    // $this->op_queue->task_ok($db, $c2_task_info['nns_op_id']);
                    // $q_report_task=true;
                    // }
//
                    // }
                    // }
                    $task_info['nns_message_id'] = (isset($task_info['nns_message_id']) && strlen($task_info['nns_message_id']) > 0) ? $task_info['nns_message_id'] : '';
                    //var_dump($q_report_task);
                    //c2任务表中存在不为终态的该任务
                    if ($q_report_task === false)
                    {
                        echo '2--';
                        echo "<br/>";
                        //if($c2_task_info!=-1){
                        if (is_array($c2_task_info) && $c2_task_info != null)
                        {
                            //修改操作id,状态
                            if ($task_info['nns_id'] != $c2_task_info['nns_op_id'])
                            {
                                //如果存在分组标示 上面的数据要一直存在队列中 等待下面的数据处理完毕才下发下去
                                if ($task_info['nns_is_group'] != 0)
                                {
                                    $temp_millisecond = round(np_millisecond_f() * 1000);
                                    nl_execute_by_db("update nns_mgtvbk_op_queue set nns_op_mtime='{$temp_millisecond}' where nns_id='{$task_info['nns_id']}'", $db);
                                    continue;
                                }
                                $set = "";
                                //存在任意一状态为终态，修改状态为等待注入
                                if ($c2_task_info['nns_status'] == 7 || $c2_task_info['nns_epg_status'] == 100)
                                {
                                    $set = ",nns_status=1,nns_epg_status=97";
                                }
                                nl_execute_by_db("update nns_mgtvbk_c2_task set nns_cp_id='{$str_c2_nns_cp_id}',nns_message_id='{$task_info['nns_message_id']}',nns_name='{$task_info['nns_name']}', nns_op_id='{$task_info['nns_id']}' $set where nns_id='{$c2_task_info['nns_id']}'", $db);
                                $this->op_queue->task_ok($db, $c2_task_info['nns_op_id']);
                                $c2_task_info['nns_op_id'] = $task_info['nns_id'];
                            }
                        }
                        //continue;
                        //}
                    }


                    //查询切片的任务的ID  便于获取切片之后的地址
                    //<update zhiyong.luo 2016-03-22 此处暂无用处，屏蔽>
//					$clip_task_id = "";
//					$clip_task_date = "";
//					if($task_info['nns_type']==BK_OP_MEDIA){
//
//						//获取切片信息
//						$clip_info = nl_db_get_one("select * from nns_mgtvbk_clip_task where nns_org_id='$sp_id' and nns_video_index_id='$nns_parent_id' and nns_video_media_id='$nns_ref_id' and nns_op_id='{$task_info['nns_id']}'  order by nns_create_time desc limit 1", $db);
//						if(is_array($clip_info)&&$clip_info!=null){
//							$clip_task_id = $clip_info['nns_id'];
//							$clip_task_date = $clip_info['nns_date'];
//						}
//
//						if(isset($task_info['nns_ex_data']['clip_id'])){
//							$clip_task_id = $task_info['nns_ex_data']['clip_id'];
//						}
//
//						if(isset($task_info['nns_ex_data']['clip_date'])){
//							$clip_task_date = $task_info['nns_ex_data']['clip_date'];
//						}
//
//
//
//					}
                    $c2_task_id = "";
                    $is_new_data = false;
                    //如果注入进来的删除命令，而且c2中又没有这个记录，并且中心同步删除指令生成c2虚拟任务开关关闭，则忽略
                    if (($c2_task_info === false || empty($c2_task_info)) && (int)$sp_conf['virtual_destroy_task'] === 0)
                    {
                        //如果注入进来的删除命令，而c2中又没有这个记录  则忽略
                        if ($task_info['nns_action'] == BK_OP_DELETE)
                        {

                            $this->op_queue->task_progress($db, $task_info['nns_id']);
                            $this->op_queue->task_ok($db, $task_info['nns_id'], $task_info, false);
                            echo '3--';
                            echo "<br/>";
                            continue;
                        }
                    }

                    //如果注入进来的修改命令，而且c2中又没有这个记录，则修改它的动作
                    if (($c2_task_info === false || empty($c2_task_info)))
                    {
                        echo '3--';
                        echo "<br/>";
                        //如果注入进来的修改命令，而c2中又没有这个记录  则将c2设置为新增
                        if ($task_info['nns_action'] == BK_OP_MODIFY)
                        {
                            $task_info['nns_action'] = BK_OP_ADD;
                        }
                    }

                    //如果存在任务就修改它的动作
                    if (is_array($c2_task_info) && $c2_task_info != null)
                    {
                        echo '4--';
                        echo "<br/>";
                        //如果列队过来的是添加动作，而C2任务中的是添加或则修改，则将c2设置为修改
                        if (($c2_task_info['nns_action'] == BK_OP_MODIFY || $c2_task_info['nns_action'] == BK_OP_ADD) && $task_info['nns_action'] == BK_OP_ADD && ((int)$c2_task_info['nns_status'] != 7 || (int)$c2_task_info['nns_epg_status'] != 100))
                        {
                            if ($q_report_task)
                            {
                                $task_info['nns_action'] = BK_OP_MODIFY;
                                //$task_info['nns_action'] = BK_OP_ADD;
                            } else
                            {
                                $task_info['nns_action'] = BK_OP_ADD;
                            }

                        }

                        //如果c2中本身是删除，而任务列队中同步的操作是添加或则修改，则按照新增处理
                        if ($c2_task_info['nns_action'] == BK_OP_DELETE && ($task_info['nns_action'] == BK_OP_MODIFY || $task_info['nns_action'] == BK_OP_ADD))
                        {
                            $task_info['nns_action'] = BK_OP_ADD;
                            echo '6--';
                            echo "<br/>";
                        }

                        //如果过来的删除炒作
                        //如果操作列队里的状态和记录表里的状态一样，则判断c2的状态是不是最终状态，如果是最终状态，则忽略，并且将操作列队的状态设置 OK
                        //if($task_info['nns_action']==BK_OP_DELETE&&$c2_task_info['nns_action']==BK_OP_DELETE){
                        //$this->op_queue->task_progress($db, $task_info['nns_id']);
                        //nl_execute_by_db("update nns_mgtvbk_c2_task set nns_modify_time=now(),nns_name='{$task_info['nns_name']}',nns where nns_id='{$c2_task_info['nns_id']}'", $db);
                        //$this->op_queue->task_ok($db, $task_info['nns_id']);
                        //echo '7--';echo "<br/>";
                        //continue;
                        //}


                        //

                        //如果主媒资或者分集队列的操作是删除，则将它的所有子级正在执行的状态设置为cancel
                        if (($task_info['nns_type'] == BK_OP_VIDEO || $task_info['nns_type'] == BK_OP_INDEX) && $task_info['nns_action'] == BK_OP_DELETE)
                        {
                            echo '8--';
                            echo "<br/>";
                            $this->__set_child_cancel($sp_id, $task_info['nns_type'], $c2_task_info['nns_ref_id']);
                        }
                        //修改状态和动作
                        $sql_c2task = "update nns_mgtvbk_c2_task  set nns_epg_fail_time=0,nns_cdn_fail_time=0,nns_cp_id='{$str_c2_nns_cp_id}',nns_is_group='{$int_nns_is_group}',nns_weight='{$int_nns_weight}',nns_message_id='{$task_info['nns_message_id']}',nns_status=" . SP_C2_WAIT . ",nns_action='{$task_info['nns_action']}',nns_modify_time=now(),nns_op_id='{$task_info['nns_id']}',nns_epg_status=" . SP_EPG_WAIT . ",nns_name='{$task_info['nns_name']}' where nns_id='{$c2_task_info['nns_id']}'";
                        //如果是片源
                        if ($task_info['nns_type'] == BK_OP_MEDIA)
                        {
                            $ex_data = "";
                            //非删除指令，修改信息
                            if ($task_info['nns_action'] != BK_OP_DELETE)
                            {
                                //if(isset($sp_conf['before_execute_sp'])&&!empty($sp_conf['before_execute_sp'])&&$task_info['nns_action']!=BK_OP_DELETE){
                                $exdata = $task_info['nns_ex_data'];
                                if (isset($exdata['url']))
                                {
                                    $ex_data .= " ,nns_file_path='" . $exdata['url'] . "' ";
                                }
                                if (isset($exdata['clip_id']))
                                {
                                    $ex_data .= " ,nns_clip_task_id='" . $exdata['clip_id'] . "' ";
                                }
                                if (isset($exdata['clip_date']))
                                {
                                    $ex_data .= " ,nns_clip_date='" . $exdata['clip_date'] . "' ";
                                }
                                if (isset($exdata['size']))
                                {
                                    $ex_data .= " ,nns_file_size='" . $exdata['size'] . "' ";
                                }
                                if (isset($exdata['file_md5']))
                                {
                                    $ex_data .= " ,nns_file_md5='" . $exdata['file_md5'] . "' ";
                                }
                                if (isset($exdata['policy']))
                                {
                                    $ex_data .= " ,nns_cdn_policy='" . $exdata['policy'] . "' ";
                                }
                            }
                            if (isset($task_info['nns_message_id']) && strlen($task_info['nns_message_id']) > 0)
                            {
                                $ex_data .= " ,nns_message_id='" . $task_info['nns_message_id'] . "' ";
                            }
                            $sql_c2task = "update nns_mgtvbk_c2_task  set nns_epg_fail_time=0,nns_cdn_fail_time=0,nns_cp_id='{$str_c2_nns_cp_id}',nns_weight='{$int_nns_weight}',nns_is_group='{$int_nns_is_group}',nns_status=" . SP_C2_WAIT . ",nns_action='{$task_info['nns_action']}',nns_modify_time=now(),nns_op_id='{$task_info['nns_id']}',nns_epg_status=" . SP_EPG_WAIT . ",nns_name='{$task_info['nns_name']}' $ex_data where nns_id='{$c2_task_info['nns_id']}'";
                        }
                        $c2_task_id = $c2_task_info['nns_id'];

                    } //如果注入进来的删除命令，而且c2中又没有这个记录，并且中心同步删除指令生成c2虚拟任务开关打开，则生成虚拟c2任务
                    elseif (!is_array($c2_task_info) && $c2_task_info === null && $task_info['nns_action'] == BK_OP_DELETE && (int)$sp_conf['virtual_destroy_task'] === 1)
                    {
                        echo '7--';
                        echo "<br/>";
                        $id = np_guid_rand($sp_id);
                        $sql_c2task = "insert into nns_mgtvbk_c2_task(nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_src_id,nns_clip_task_id,nns_clip_date,nns_op_id,nns_epg_status,nns_message_id,nns_is_group,nns_weight,nns_cp_id) values ('$id','{$task_info['nns_type']}','{$task_info['nns_name']}','$nns_ref_id','" . BK_OP_DELETE . "'," . SP_C2_WAIT . ",now(),'$sp_id','$nns_parent_id',null,null,'{$task_info['nns_id']}'," . SP_EPG_WAIT . ",'{$task_info['nns_message_id']}','{$int_nns_is_group}','{$int_nns_weight}','{$str_c2_nns_cp_id}')";
                    }
                    else
                    {
                        echo '9--';
                        echo "<br/>";

                        //如果获取的操作队列动作为删除或者c2没有注入，则将转台修改为添加
                        $id = np_guid_rand($sp_id);

                        $sql_c2task = "insert into nns_mgtvbk_c2_task(nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_src_id,nns_clip_task_id,nns_clip_date,nns_op_id,nns_epg_status,nns_message_id,nns_is_group,nns_weight,nns_cp_id) values ('$id','{$task_info['nns_type']}','{$task_info['nns_name']}','$nns_ref_id','" . BK_OP_ADD . "'," . SP_C2_WAIT . ",now(),'$sp_id','$nns_parent_id',null,null,'{$task_info['nns_id']}'," . SP_EPG_WAIT . ",'{$task_info['nns_message_id']}','{$int_nns_is_group}','{$int_nns_weight}','{$str_c2_nns_cp_id}')";
                        $ex_data_filter = "";
                        $ex_data_filter_value = "";
                        if ($task_info['nns_type'] == BK_OP_MEDIA)
                        {
                            if ($task_info['nns_action'] != BK_OP_DELETE)
                            {
                                //if(isset($sp_conf['before_execute_sp'])&&!empty($sp_conf['before_execute_sp'])&&$task_info['nns_action']!=BK_OP_DELETE){
                                $exdata = $task_info['nns_ex_data'];
                                //$ex_data_filter = ",nns_file_path,nns_clip_task_id,nns_clip_date,nns_file_size,nns_file_md5,nns_cdn_policy";
                                //$ex_data_filter_value = " ,'".$exdata['url']."','".$exdata['clip_id']."' ,'".$exdata['clip_date']."','".$exdata['size']."' ,'".$exdata['file_md5']."','".$exdata['policy']."'";
                                if (isset($exdata['url']))
                                {
                                    $ex_data_filter .= ",nns_file_path";
                                    $ex_data_filter_value .= ",'" . $exdata['url'] . "'";
                                }
                                if (isset($exdata['clip_id']))
                                {
                                    $ex_data_filter .= ",nns_clip_task_id";
                                    $ex_data_filter_value .= ",'" . $exdata['clip_id'] . "'";
                                }
                                if (isset($exdata['clip_date']))
                                {
                                    $ex_data_filter .= ",nns_clip_date";
                                    $ex_data_filter_value .= ",'" . $exdata['clip_date'] . "'";
                                }
                                if (isset($exdata['size']))
                                {
                                    $ex_data_filter .= ",nns_file_size";
                                    $ex_data_filter_value .= ",'" . $exdata['size'] . "'";
                                }
                                if (isset($exdata['file_md5']))
                                {
                                    $ex_data_filter .= ",nns_file_md5";
                                    $ex_data_filter_value .= ",'" . $exdata['file_md5'] . "'";
                                }
                                if (isset($exdata['policy']))
                                {
                                    $ex_data_filter .= ",nns_cdn_policy";
                                    $ex_data_filter_value .= ",'" . $exdata['policy'] . "'";
                                }
                            }
                            if (isset($task_info['nns_message_id']) && strlen($task_info['nns_message_id']) > 0)
                            {
                                $ex_data_filter .= ",nns_message_id";
                                $ex_data_filter_value .= ",'" . $task_info['nns_message_id'] . "'";
                            }
                            $sql_c2task = "insert into nns_mgtvbk_c2_task(nns_cp_id,nns_weight,nns_is_group,nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_src_id,nns_op_id,nns_epg_status" . $ex_data_filter . ") values ('{$str_c2_nns_cp_id}','{$int_nns_weight}','{$int_nns_is_group}','$id','{$task_info['nns_type']}','{$task_info['nns_name']}','$nns_ref_id','" . BK_OP_ADD . "'," . SP_C2_WAIT . ",now(),'$sp_id','$nns_parent_id','{$task_info['nns_id']}','" . SP_EPG_WAIT . "'" . $ex_data_filter_value . ")";
                        }
                        $c2_task_id = $id;
                        $is_new_data = true;
                    }
                    //echo $sql_c2task;
                    $result = nl_execute_by_db($sql_c2task, $db);

                    //var_dump($result);
                    //插入成功	 修改列队状态
                    if ($result)
                    {
                        if ($task_info['nns_type'] == BK_OP_MEDIA && $task_info['nns_action'] == BK_OP_DELETE && (int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
                        {
                            //如果是删除命令，并且是片源，就需要将切片里面的切片日志记录删除掉
                            $update_clip_state = "update nns_mgtvbk_clip_task set nns_state='cancel',nns_task_name='{$task_info['nns_name']}' where nns_org_id='$sp_id' and nns_video_id='{$task_info['nns_video_id']}' and nns_video_index_id='{$task_info['nns_index_id']}' and nns_video_media_id='{$task_info['nns_media_id']}'";
                            nl_execute_by_db($update_clip_state, $db);
                        }
                        //添加计数+1

                        if ($task_info['nns_type'] == 'video')
                        {
                            $num_video++;
                        } elseif ($task_info['nns_type'] == 'index')
                        {
                            $num_index++;
                        } elseif ($task_info['nns_type'] == 'media')
                        {
                            $num_media++;
                        }

                        //$this->op_queue->task_progress($db, $sp_id, $nns_ref_id, $task_info['nns_type']);
                        $this->op_queue->task_progress($db, $task_info['nns_id']);
                    }
                    //echo "task_end-".date('Y-m-d H:i:s')."<br/>";
                    //echo PHP_EOL;
                    echo "RunTime:" . np_runtime_ex('task' . $task_info['nns_id'], true);
                    //echo PHP_EOL;
                }
            }
        }
    }


    /**
     * 将所有子级状态设置为cancel
     *
     *
     */
    private function __set_child_cancel($sp_id, $nns_type, $nns_video_id)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        switch ($nns_type)
        {
            case BK_OP_VIDEO:
                $sql_index = "select * from nns_mgtvbk_c2_task where nns_type='" . BK_OP_INDEX . "' and nns_org_id='$sp_id' and nns_src_id='$nns_video_id'";
                $index_infos = nl_db_get_all($sql_index, $db);
                foreach ($index_infos as $index)
                {
                    $this->__set_child_cancel($sp_id, BK_OP_INDEX, $index['nns_ref_id']);
                    //$q_report_task=true是最终状态
                    $sp_config = sp_model::get_sp_config($index['nns_org_id'], $index['nns_type'] . '_' . $index['nns_action']);
                    $q_report_task = $this->is_succ_state($sp_config, $index);
                    //不是最终状态，任务为添加或者修改主媒资，取消该操作任务
                    if ($q_report_task === false && ($index['nns_action'] == BK_OP_ADD || $index['nns_action'] == BK_OP_MODIFY))
                    {
                        $op_id = $index['nns_op_id'];
                        $this->op_queue->task_cancel($db, $op_id);

                        nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100   where nns_id='{$index['nns_id']}'", $db);
                    }
                }
                break;

            case BK_OP_INDEX:
                $sql_media = "select * from nns_mgtvbk_c2_task where nns_type='" . BK_OP_MEDIA . "' and nns_org_id='$sp_id' and nns_src_id='$nns_video_id'";
                $media_infos = nl_db_get_all($sql_media, $db);
                foreach ($media_infos as $media)
                {
                    //$q_report_task=true是最终状态
                    $sp_config = sp_model::get_sp_config($media['nns_org_id'], $media['nns_type'] . '_' . $media['nns_action']);
                    $q_report_task = $this->is_succ_state($sp_config, $media);
                    if ($q_report_task === false && ($media['nns_action'] == BK_OP_ADD || $media['nns_action'] == BK_OP_MODIFY))
                    {
                        $op_id = $media['nns_op_id'];
                        $this->op_queue->task_cancel($db, $op_id);
                        nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100   where nns_id='{$media['nns_id']}'", $db);
                    }
                }
                break;
        }
    }


    /**
     * 上报状态
     */
    public function q_report_task($c2_task_id)
    {
        //上报状态，查询这个动作是不是最终状态，如果是最终状态则上报到操作列队OK
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $sql = "select * from nns_mgtvbk_c2_task where nns_id='$c2_task_id'";
        $c2_task_info = nl_db_get_one($sql, $db);
        // print_r($c2_task_info);die;
        //计算这个任务的最终状态
        if (is_array($c2_task_info) && $c2_task_info != null)
        {
            $sp_config = sp_model::get_sp_config($c2_task_info['nns_org_id'], $c2_task_info['nns_type'] . '_' . $c2_task_info['nns_action']);
            //判断是不是最终状态
            $q_report_task = $this->is_succ_state($sp_config, $c2_task_info);
            // return $q_report_task;
            //die;
            if ($q_report_task === true)
            {
                //获取这个sp的后置sp
                $sp_config = sp_model::get_sp_config($c2_task_info['nns_org_id']);
                //print_r($sp_config);die;
                if (isset($sp_config['after_execute_sp']) && !empty($sp_config['after_execute_sp']))
                {
                    //获取前置sp的列队信息
                    //print_r($c2_task_info);die;
                    if ($c2_task_info['nns_op_id'])
                    {
                        //获取操作队列信息
                        $op_before_detail = $this->get_q_task_detail($c2_task_info['nns_op_id']);
                        //获取后置sp的相同单位的队列id
                        $params = array(
                            'video_id' => $op_before_detail['q_task_info']['nns_video_id'],
                            'index_id' => $op_before_detail['q_task_info']['nns_index_id'],
                            'media_id' => $op_before_detail['q_task_info']['nns_media_id'],
                            'org_id' => $sp_config['after_execute_sp'],
                            'type' => $op_before_detail['q_task_info']['nns_type'],
                            'action' => $op_before_detail['q_task_info']['nns_action'],
                            'message_id' => $op_before_detail['q_task_info']['nns_message_id']
                        );
                        //添加相同操作到后置sp
                        $op_after = $this->__q_get_after_op($op_before_detail, $params);

                        if ((int)$op_after['state'] === 100)
                        {
                            $op_after_id = $op_after['data'];//获取后置opid
                            $ex_url = '';
                            if ($c2_task_info['nns_type'] == 'media' && $c2_task_info['nns_type'] != 'destroy')
                            {
                                $c2_task_info_exdata = $c2_task_info['nns_ex_url'];
                                $ex_url = json_encode(array(
                                    'url' => $c2_task_info_exdata,
                                    'path' => $c2_task_info_exdata,
                                    'size' => $c2_task_info['nns_file_size'],
                                    'clip_id' => $c2_task_info['nns_clip_task_id'],
                                    'clip_date' => $c2_task_info['nns_clip_date'],
                                    'file_md5' => $c2_task_info['nns_file_md5'],
                                    'policy' => $c2_task_info['nns_cdn_policy'],
                                ));
                                //nl_execute_by_db("update nns_mgtvbk_op_queue set nns_ex_data='$ex_url' where nns_id='$op_after_id'", $db);
                            }
                            //更新nns_mgtvbk_op_queue表信息
                            $rs = $this->op_queue->wait_op_execute($db, $op_after_id, $ex_url);
                            if ((int)$rs['state'] == 100)
                            {
                                //如果获取到后置的任务才将前置设置为ok
                                $r = $this->op_queue->task_ok($db, $c2_task_info['nns_op_id'], $c2_task_info);
                            }
                        }
                    }
                } else
                {
                    if ($c2_task_info['nns_org_id'] != 'jsyx')
                    {
                        $r = $this->op_queue->task_ok($db, $c2_task_info['nns_op_id'], $c2_task_info);
                    } else
                    {
                        //江苏有线
                        $r = array('state' => 100, 'reason' => 'OK', 'data' => '');
                    }
                }
                return $r;
            } else
            {
                return false;
            }
        }
    }


    /**
     * $op_before_detail  = array（
     *    nns_id,
     *    nns_......
     * ）
     * @$params  = array()
     *
     * @return
     */
    private function __q_get_after_op($op_before_detail, $params)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $re = $this->op_queue->get_op_id($db, $params);
        if ((int)$re['state'] === 103)
        {
            //没有获取到id，就要给后置去添加一个相同单位相同操作的信息
            $video_id = $params[$params['type'] . '_id'];
            $this->q_add_task($video_id, $params['type'], $params['action'], $params['org_id'], null, false, $params['message_id']);
            $re = $this->op_queue->get_op_id($db, $params);
        }
        return $re;
    }

    /**
     * 判断是不是最终状态
     *
     */
    public function is_succ_state($sp_config, $c2_task_info)
    {
        set_time_limit(0);

        if (empty($c2_task_info))
        {
            return true;
        }

        if ((int)$c2_task_info['nns_status'] === 7 || (int)$c2_task_info['nns_epg_status'] === 100)
        {
            return true;
        }

        if ($c2_task_info['nns_status'] == -1)
        {
            return false;
        }

        $q_report_task = false;

        //EGP优先
        if ((int)$sp_config['priority'] === 1)
        {
            //全部注入
            if ((int)$sp_config['status'] === 0)
            {
                if ((int)$c2_task_info['nns_status'] === 0 && (int)$c2_task_info['nns_epg_status'] === 99)
                {
                    $q_report_task = true;
                }
                //只注入CDN
            } elseif ((int)$sp_config['status'] === 1)
            {
                if ((int)$c2_task_info['nns_status'] === 0)
                {
                    $q_report_task = true;
                }
                //只注入EPG
            } elseif ((int)$sp_config['status'] === 2)
            {
                if ((int)$c2_task_info['nns_epg_status'] === 99)
                {
                    $q_report_task = true;
                }
            }
            //CDN优先
        } elseif ((int)$sp_config['priority'] === 0)
        {
            //全部注入
            if ((int)$sp_config['status'] === 0)
            {
                if ((int)$c2_task_info['nns_status'] === 0 && (int)$c2_task_info['nns_epg_status'] === 99)
                {
                    $q_report_task = true;
                }
                //只注入CDN
            } elseif ((int)$sp_config['status'] === 1)
            {
                if ((int)$c2_task_info['nns_status'] === 0)
                {
                    $q_report_task = true;
                }
                //只注入EPG
            } elseif ((int)$sp_config['status'] === 2)
            {
                if ((int)$c2_task_info['nns_epg_status'] === 99)
                {
                    $q_report_task = true;
                }
            }
        }

        return $q_report_task;
    }

    /**
     * 上报切片状态
     *
     */
    public function q_clip_ok($task_id)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $sql = "select * from nns_mgtvbk_clip_task where nns_id='$task_id'";
        $clip_info = nl_db_get_one($sql, $db);
        if (is_array($clip_info) && $clip_info != null)
        {
            $org_id = $clip_info['nns_org_id'];
            $media_id = $clip_info['nns_video_media_id'];
            $nns_op_id = $clip_info['nns_op_id'];
            $r = $this->op_queue->clip_ok($db, $nns_op_id);
            if ($clip_info['nns_state'] == 'ok')
            {
                return true;
            }
            //print_r($r);
            //如果切片任务中没有这个，则将切片任务
            // if((int)$r['state']===103){
            // //设置切片任务为cancel
            // $sql_clip_task = "update nns_mgtvbk_clip_task set nns_state='cancel',nns_desc='任务取消' where nns_id='$task_id'";
            // nl_execute_by_db($sql_clip_task, $db);
            // }
        }
    }

    
    
    
    public function make_time($time)
    {
        return date("H:i:s",$time);
    }

    /**
     * 在切片的时候推送数据
     *
     */
    public function q_clip_ok_push($task_id, $nns_date = null, $nns_new_dir = null, $nns_path = null, $nns_file_size = null, $nns_file_md5 = null, $nns_cdn_policy = null, $nns_node_id = null, $nns_list_ids = null,$arr_sp_config=null,$media_arr_ex=null)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $sql = "select * from nns_mgtvbk_clip_task where nns_id='$task_id'";
        $clip_info = nl_db_get_one($sql, $db);
        if (is_array($clip_info) && $clip_info != null)
        {
            $sp_id = $org_id = $clip_info['nns_org_id'];
            // $media_id = $clip_info['nns_video_media_id'];
            // $media_info = nl_db_get_one("select concat(vodindex.nns_name,'_',media.nns_mode) as nns_name,media.nns_vod_index_id as nns_index_id,vodindex.nns_index as nns_index_num, media.nns_vod_id  as nns_vod_id from nns_vod_media media left join nns_vod_index vodindex on media.nns_vod_index_id=vodindex.nns_id   where media.nns_id='{$media_id}'", $db);
            // $nns_ref_id = $clip_info['nns_video_media_id'];
            // $nns_parent_id = $media_info['nns_index_id'];
            // $nns_vod_id = $media_info['nns_vod_id'];
            // $task_name = $media_info['nns_name'];
            // unset($media_info);

            if (empty($nns_date))
            {
                $nns_date = $clip_info['nns_date'];
            }
            //查询拼音
            //$nns_vod_info = video_model::get_vod_info($clip_info['nns_video_id']);
            //$pinyin = $nns_vod_info['nns_pinyin'];unset($nns_vod_info);
            //查询c2表中有没有数据
            // $c2_info = nl_db_get_one("select * from nns_mgtvbk_c2_task where nns_org_id='$org_id' and nns_type='".BK_OP_MEDIA."' and nns_ref_id='$nns_ref_id'", $db);
//
            // if(is_array($c2_info)&&!empty($c2_info)){
            // $sql_c2task = "update nns_mgtvbk_c2_task set nns_file_path='$nns_path',nns_file_size='$nns_file_size',nns_file_md5='$nns_file_md5',nns_clip_task_id='$task_id',nns_clip_date='$nns_date',nns_cdn_policy='{$nns_cdn_policy}',nns_status=7,nns_epg_status=100,nns_type='".BK_OP_MEDIA."',nns_action='".BK_OP_ADD."'  where nns_id='{$c2_info['nns_id']}'";
            // }else{
            // $id = np_guid_rand();
            // $sql_c2task = "insert into nns_mgtvbk_c2_task(nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_src_id,nns_clip_task_id,nns_clip_date,nns_op_id,nns_epg_status,nns_file_path,nns_file_size,nns_file_md5,nns_cdn_policy) values ('$id','".BK_OP_MEDIA."','{$task_name}','$nns_ref_id','".BK_OP_ADD."',7,now(),'$sp_id','$nns_parent_id','$task_id','$clip_task_date','',100,'$nns_path','$nns_file_size','$nns_file_md5','$nns_cdn_policy')";
            // }
            // nl_execute_by_db($sql_c2task, $db);
            $sql_media = "select * from nns_vod_media where nns_id='{$clip_info['nns_video_media_id']}' limit 1";
            $media_info = nl_db_get_one($sql, $db);
            if (isset($media_info['nns_cp_id']) && $media_info['nns_cp_id'] == 'manual_import_pc')
            {
                $nns_path = 'manual_import/' . $nns_path;
            }
            
            

            $ext_data = array(
                'url' => $nns_path,
                'path' => $nns_path,
                'size' => $nns_file_size,
                'clip_id' => $task_id,
                'clip_date' => $nns_date,
                'file_md5' => $nns_file_md5,
                'policy' => $nns_cdn_policy,
                'node_id' => $nns_node_id,
                'list_ids' => $nns_list_ids
            );

            $op_id = $clip_info['nns_op_id'];
            //处理json之后中文转码的问题 feijian.gao -->start
            $ext_data_info = json_encode($ext_data, JSON_UNESCAPED_UNICODE);
            //处理json之后中文转码的问题 feijian.gao -->end
            $sql = "update nns_mgtvbk_op_queue set nns_ex_data='" . $ext_data_info . "' where nns_id='{$op_id}'";

            nl_execute_by_db($sql, $db);

            $str_set = '';

            if (is_array($media_info))
            {
                $nns_file_size = (int)$nns_file_size > 0 ? (int)$nns_file_size : 0;
                $media_info['nns_file_size'] = $media_info['nns_file_size'] > 0 ? $media_info['nns_file_size'] : 0;
                $temp_file_size = $nns_file_size > 0 ? $nns_file_size : $media_info['nns_file_size'];
                $temp_file_size = $temp_file_size > 0 ? $temp_file_size : 8080;
                $str_set .= ",nns_file_size='{$temp_file_size}'";
                if(isset($media_arr_ex['BeatRate']) && !empty($media_arr_ex['BeatRate']))
                {
                    $media_arr_ex['BeatRate'] = floor($media_arr_ex['BeatRate']/1024);
                    $str_set .= ",nns_kbps='{$media_arr_ex['BeatRate']}'";
                }
                if(isset($media_arr_ex['RunTime']) && !empty($media_arr_ex['RunTime']))
                {
                    $str_set .= ",nns_file_time_len='{$media_arr_ex['RunTime']}'";
                }
                if(isset($media_arr_ex['RunTime']) && !empty($media_arr_ex['RunTime']))
                {
                    $str_set .= ",nns_file_time_len='{$media_arr_ex['RunTime']}'";
                }
            }
            if(isset($arr_sp_config['clip_set_playurl']) && strlen($arr_sp_config['clip_set_playurl']) >0)
            {
                $arr_sp_config['clip_set_playurl'] = trim(rtrim(rtrim($arr_sp_config['clip_set_playurl'],'/'),'\\'));
                $temp_nns_path = trim(ltrim(ltrim($nns_path,'/'),'\\'));
                $arr_playurl = array(
                    'play_url'=>$arr_sp_config['clip_set_playurl'].'/'.$temp_nns_path,
                );
                $str_playurl = json_encode($arr_playurl);
                $str_set .= ",nns_ext_url='{$str_playurl}'";
            }
            //新增修改片源扩展信息
            $media_sql = "update nns_vod_media set nns_ext_info='" . $ext_data_info . "'{$str_set} where nns_id='{$clip_info['nns_video_media_id']}'";
            nl_execute_by_db($media_sql, $db);

            /*
			$check_index = nl_db_get_one("select * from nns_mgtvbk_c2_task where nns_type='index' and nns_org_id='$sp_id' and nns_ref_id='$nns_parent_id'", $db);
			if(is_array($check_index)&&$check_index!=null){
				if($check_index['nns_action']==BK_OP_DELETE){
					nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=1,nns_epg_status=97,nns_action='add' where nns_id='{$check_index['nns_id']}'", $db);
				}
			}else{
				$index_info = video_model::get_vod_index_info($nns_parent_id);
				$id_index =  np_guid_rand();
				$sql_index_insert = "insert into nns_mgtvbk_c2_task(nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_epg_status,nns_src_id)values('$id_index','index','{$index_info['nns_name']}','$nns_parent_id','add',1,now(),'$sp_id',97,'$nns_vod_id')";
				nl_execute_by_db($sql_index_insert, $db);
			}







			$check_vod = nl_db_get_one("select * from nns_mgtvbk_c2_task where nns_type='video' and nns_org_id='$sp_id' and nns_ref_id='$nns_vod_id'", $db);
			if(is_array($check_vod)&&$check_vod!=null){
				if($check_vod['nns_action']==BK_OP_DELETE){
					nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=1,nns_epg_status=97,nns_action='add' where nns_id='{$check_vod['nns_id']}'", $db);
				}
			}else{
				$vod_info = video_model::get_vod_info($nns_vod_id);
				$idv_index =  np_guid_rand();
				$sql_vod_insert = "insert into nns_mgtvbk_c2_task(nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_epg_status)values('$idv_index','video','{$vod_info['nns_name']}','$nns_vod_id','add',1,now(),'$sp_id',97)";
				nl_execute_by_db($sql_vod_insert, $db);
			}



			*/


        }

        unset($db);
    }

    
    public function get_media_info($ftp_url,$media_url)
    {
        include_once dirname(dirname(dirname(__FILE__))).'/v2/ns_core/m_mediainfo.class.php';
        $media_info_guid = dirname(dirname(dirname(__FILE__))).'/data/temp/mediainfo/temp';
        if (!is_dir($media_info_guid))
        {
            mkdir($media_info_guid, 0777, true);
        }
        $media_info_guid.=np_guid_rand().'.xml';
        
        $ftp_url = trim(trim(trim($ftp_url,'/'),'\\'));
        $media_url = trim(trim(trim($media_url,'/'),'\\'));
        
        $medi_url = $ftp_url.'/'.$media_url;
        $result = m_mediainfo::exec_ftp($ftp_url.'/'.$media_url,$media_info_guid);
        $arr_media_info = null;
        if($result['ret'] == '0' && strlen($result['data_info']) >0)
        {
            $arr_media_info = simplexml_load_string($result['data_info']);
            $arr_media_info = json_decode(json_encode($arr_media_info),true);
        }
        $result = null;
        $Duration = isset($arr_media_info['File']['track'][0]['Duration'][0]) ? (int)$arr_media_info['File']['track'][0]['Duration'][0] : 45*60*60;
        $result['RunTime'] = $Duration;
        $result['BeatRate'] = isset($arr_media_info['File']['track'][0]['Overall_bit_rate'][0]) ? (int)$arr_media_info['File']['track'][0]['Overall_bit_rate'][0] : 2.3*1024*1024;
        $result['FileSize'] = isset($arr_media_info['File']['track'][0]['File_size'][0]) ? (int)$arr_media_info['File']['track'][0]['File_size'][0] : 384061252;
        $result['FrameHeight'] = (isset($arr_media_info['File']['track'][1]['Sampled_Height']) && (int)$arr_media_info['File']['track'][1]['Sampled_Height']>0) ? (int)$arr_media_info['File']['track'][1]['Sampled_Height'] : 1080;
        $result['FrameWidth'] = (isset($arr_media_info['File']['track'][1]['Sampled_Width']) && (int)$arr_media_info['File']['track'][1]['Sampled_Width']>0) ? (int)$arr_media_info['File']['track'][1]['Sampled_Width'] : 1920;
        $media_formart = isset($arr_media_info['File']['track'][0]['Overall_bit_rate_mode'][0]) ? $arr_media_info['File']['track'][0]['Overall_bit_rate_mode'][0] : '';
        $result['media_formart'] = is_string($media_formart) ? strtoupper($media_formart) : '';
        return $result;
    }
    

    /**
     * 获取切片任务
     */

    public function q_get_clip_task($sp_id, $num = 3)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $re = $this->op_queue->get_clip($db, $sp_id, $num);
        //print_r($re);die;

        //从操作列队中获取的任务添加到切片任务表中，由切片程序获取任务使用
        if ($re['state'] == 100 && is_array($re['data']) && !empty($re['data']))
        {
            foreach ($re['data'] as $q_clip_task_info)
            {
                //判断当前的片源任务是否是在任务表中是否是最终状态，如果不是最终状态，则忽略
                //var_dump($q_clip_task_info);
                //$sql="select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and  nns_type='media' and nns_ref_id='{$q_clip_task_info['nns_media_id']}' and nns_src_id='{$q_clip_task_info['nns_index_id']}'";
                //$c2_task_info = nl_db_get_one($sql, $db);
                //var_dump($c2_task_info);				die;
                //$sp_config = sp_model::get_sp_config($sp_id, 'video_'.$c2_task_info['nns_action']);
                //if(is_array($c2_task_info)&&$c2_task_info!=null){
                //if($c2_task_info['nns_status']!=$sp_config['status']){
                //	continue;
                //}
                //}else{

                //添加切片任务
                $nns_video_type = 0;
                if ($q_clip_task_info['nns_type'] == 'file')
                {
                    $nns_video_type = 2;
                } elseif ($q_clip_task_info['nns_type'] == 'live_media')
                {
                    $nns_video_type = 1;
                }

                $clip_params = array(
                    'nns_video_type' => $nns_video_type,
                    'nns_video_id' => $q_clip_task_info['nns_video_id'],
                    'nns_video_index_id' => $q_clip_task_info['nns_index_id'],
                    'nns_video_media_id' => $q_clip_task_info['nns_media_id'],
                    'nns_task_name' => $q_clip_task_info['nns_name'],
                    'nns_op_id' => $q_clip_task_info['nns_id'],
                    'nns_org_id' => $sp_id,
                    'nns_priority' => isset($q_clip_task_info['nns_weight']) ? (int)$q_clip_task_info['nns_weight'] : 0,
                    'nns_cp_id' => isset($q_clip_task_info['nns_cp_id']) ? $q_clip_task_info['nns_cp_id'] : '',
                );
                $clip_result = clip_task_model::add_task($clip_params);
                if ($clip_result === true)
                {
                    $this->op_queue->clip_progress($db, $q_clip_task_info['nns_id']);
                }
            }
        }
    }

    /**
     * 处理正在转码的进度
     */
    public function get_encode_clip_fail_task($num, $result_clip_task_fail = null)
    {
        set_time_limit(0);
        if (!isset($result_clip_task_fail['data_info']) || empty($result_clip_task_fail['data_info']) || !is_array($result_clip_task_fail['data_info']))
        {
            $result_clip_task_fail = nl_clip_task::get_info_by_state_sp($this->dc, $this->op_sp, 'clip_encode_fail', $num);
        }
        if ($result_clip_task_fail['ret'] != 0 || empty($result_clip_task_fail['data_info']) || !is_array($result_clip_task_fail['data_info']))
        {
            return $result_clip_task_fail;
        }
        foreach ($result_clip_task_fail['data_info'] as $key => $val)
        {
            $result_del = $this->file_del($val['nns_id']);
            if ($result_del['ret'] != 0)
            {
                $this->error_infos[] = $result_del['reason'];
                unset($result_clip_task_fail['data_info'][$key]);
                continue;
            }
        }
        if (is_array($result_clip_task_fail['data_info']) && !empty($result_clip_task_fail['data_info']))
        {
            return $this->get_encode_clip_task(0, $result_clip_task_fail);
        }
        return $this->_return_result_data(0, var_export($this->error_info, true));
    }


    /**
     * 处理正在转码的进度
     */
    public function get_encode_clip_load_task()
    {
        set_time_limit(0);
        $result_clip_task_ok = nl_clip_task::get_info_by_state_sp($this->dc, $this->op_sp, 'clip_encode_ok');
        if ($result_clip_task_ok['ret'] != 0)
        {
            return $result_clip_task_ok;
        }
        if (is_array($result_clip_task_ok['data_info']) && !empty($result_clip_task_ok['data_info']))
        {
            foreach ($result_clip_task_ok['data_info'] as $val)
            {
                $arr_log = array(
                    'nns_task_id' => $val['nns_id'],
                    'nns_state' => 'ok',
                    'nns_desc' => 'ok',
                    'nns_video_type' => $val['nns_video_type'],
                    'nns_video_id' => $val['nns_video_id'],
                    'nns_video_index_id' => $val['nns_video_index_id'],
                    'nns_org_id' => $this->op_sp,
                );
                nl_clip_task_log::add($this->dc, $arr_log);
                nl_clip_task::edit($this->dc, array('nns_state' => 'ok'), $val['nns_id']);
                nl_op_queue::edit($this->dc, array('nns_status' => 0), $val['nns_op_id']);
                $this->q_clip_ok($val['nns_id']);
            }
        }
        $result_clip_task_load = nl_clip_task::get_info_by_state_sp($this->dc, $this->op_sp, 'clip_encode_loading');
        if ($result_clip_task_load['ret'] != 0 || empty($result_clip_task_load['data_info']) || !is_array($result_clip_task_load['data_info']))
        {
            return $result_clip_task_load;
        }
        if (!isset($this->sp_config['clip_file_encode_api_url']) || strlen($this->sp_config['clip_file_encode_api_url']) < 1)
        {
            return $this->_return_result_data(1, '转码请求API接口为空:' . $this->sp_config['clip_file_encode_api_url']);
        }
        if (empty($this->sp_config_encode_url) || !is_array($this->sp_config_encode_url))
        {
            $this->sp_config_encode_url = array_filter(explode(';', $this->sp_config['clip_file_encode_api_url']));
            if (!is_array($this->sp_config_encode_url) || empty($this->sp_config_encode_url))
            {
                return $this->_return_result_data(1, 'arr转码请求API接口为空:' . var_export($this->sp_config_encode_url, true));
            }
        }
        $arr_file_encode_api_url = $this->query_load_balance();
        if ($arr_file_encode_api_url['ret'] != 0 || !isset($arr_file_encode_api_url['data_info']) || empty($arr_file_encode_api_url['data_info']) || !is_array($arr_file_encode_api_url['data_info']))
        {
            return $this->_return_result_data(1, 'arr转码请求API接口为空:' . var_export($arr_file_encode_api_url, true));
        }
        $arr_file_encode_api_url = $arr_file_encode_api_url['data_info'];
        foreach ($result_clip_task_load['data_info'] as $val)
        {
            $re_queue = nl_op_queue::query_op_queue_info_by_id($this->dc, $val['nns_op_id']);
            if ($re_queue['ret'] != 0 || !isset($re_queue['data_info'][0]['nns_encode_flag']) || empty($re_queue['data_info'][0]['nns_encode_flag']))
            {
                $arr_log = array(
                    'nns_task_id' => $val['nns_id'],
                    'nns_state' => 'encode_error',
                    'nns_desc' => '转码失败查询op_queue:' . var_export($re_queue, true),
                    'nns_video_type' => $val['nns_video_type'],
                    'nns_video_id' => $val['nns_video_id'],
                    'nns_video_index_id' => $val['nns_video_index_id'],
                    'nns_org_id' => $this->op_sp,
                );
                nl_clip_task_log::add($this->dc, $arr_log);
                nl_clip_task::edit($this->dc, array('nns_state' => 'clip_encode_fail'), $val['nns_id']);
                continue;
            }
            if (!isset($arr_file_encode_api_url[$re_queue['data_info'][0]['nns_encode_flag']]))
            {
                $arr_log = array(
                    'nns_task_id' => $val['nns_id'],
                    'nns_state' => 'encode_error',
                    'nns_desc' => '转码失败未设置encode_flag:' . var_export($arr_file_encode_api_url, true),
                    'nns_video_type' => $val['nns_video_type'],
                    'nns_video_id' => $val['nns_video_id'],
                    'nns_video_index_id' => $val['nns_video_index_id'],
                    'nns_org_id' => $this->op_sp,
                );
                nl_clip_task_log::add($this->dc, $arr_log);
                nl_clip_task::edit($this->dc, array('nns_state' => 'clip_encode_fail'), $val['nns_id']);
                continue;
            }
            $result_state = $this->file_state($val['nns_id'], $arr_file_encode_api_url[$re_queue['data_info'][0]['nns_encode_flag']]);
            if ($result_state['ret'] != 0)
            {
                $arr_log = array(
                    'nns_task_id' => $val['nns_id'],
                    'nns_state' => 'encode_error',
                    'nns_desc' => '转码失败' . var_export($result_state['reason'], true),
                    'nns_video_type' => $val['nns_video_type'],
                    'nns_video_id' => $val['nns_video_id'],
                    'nns_video_index_id' => $val['nns_video_index_id'],
                    'nns_org_id' => $this->op_sp,
                );
                nl_clip_task_log::add($this->dc, $arr_log);
                nl_clip_task::edit($this->dc, array('nns_state' => 'clip_encode_fail'), $val['nns_id']);
                $this->error_infos[] = $result_state['reason'];
            } else
            {
                $arr_log = array(
                    'nns_task_id' => $val['nns_id'],
                    'nns_state' => 'encode_loading',
                    'nns_desc' => '转码进度' . $result_state['data_info'] . "%",
                    'nns_video_type' => $val['nns_video_type'],
                    'nns_video_id' => $val['nns_video_id'],
                    'nns_video_index_id' => $val['nns_video_index_id'],
                    'nns_org_id' => $this->op_sp,
                );
                nl_clip_task_log::add($this->dc, $arr_log);
                if ($result_state['data_info'] == 100)
                {
                    $arr_log = array(
                        'nns_task_id' => $val['nns_id'],
                        'nns_state' => 'encode_ok',
                        'nns_desc' => "转码完成clip_encode_ok",
                        'nns_video_type' => $val['nns_video_type'],
                        'nns_video_id' => $val['nns_video_id'],
                        'nns_video_index_id' => $val['nns_video_index_id'],
                        'nns_org_id' => $this->op_sp,
                    );
                    nl_clip_task_log::add($this->dc, $arr_log);
                    nl_clip_task::edit($this->dc, array('nns_state' => 'clip_encode_ok'), $val['nns_id']);
                }
            }
        }
    }

    /**
     * 处理等待转码的数据进度
     */
    public function get_encode_clip_task($num, $result_clip_task_wait = null)
    {
        set_time_limit(0);
        if (!isset($result_clip_task_wait) || !is_array($result_clip_task_wait) || empty($result_clip_task_wait))
        {
            $result_clip_task_wait = nl_clip_task::get_info_by_state_sp($this->dc, $this->op_sp, 'clip_encode_wait', $num);
            if ($result_clip_task_wait['ret'] != 0 || empty($result_clip_task_wait['data_info']) || !is_array($result_clip_task_wait['data_info']))
            {
                return $result_clip_task_wait;
            }
        }
        if (!is_array($result_clip_task_wait['data_info']) || empty($result_clip_task_wait['data_info']))
        {
            return $this->_return_result_data(0, 'ok');
        }
        if (!isset($this->sp_config['clip_file_encode_api_url']) || strlen($this->sp_config['clip_file_encode_api_url']) < 1)
        {
            return $this->_return_result_data(1, '转码请求API接口为空:' . $this->sp_config['clip_file_encode_api_url']);
        }
        if (empty($this->sp_config_encode_url) || !is_array($this->sp_config_encode_url))
        {
            $this->sp_config_encode_url = array_filter(explode(';', $this->sp_config['clip_file_encode_api_url']));
            if (!is_array($this->sp_config_encode_url) || empty($this->sp_config_encode_url))
            {
                return $this->_return_result_data(1, 'arr转码请求API接口为空:' . var_export($this->sp_config_encode_url, true));
            }
        }
        foreach ($result_clip_task_wait['data_info'] as $val)
        {
            $result_op_queue = nl_op_queue::query_op_queue_info_by_id($this->dc, $val['nns_op_id']);
            if ($result_op_queue['ret'] != 0)
            {
                return $result_op_queue;
            }
            if (!isset($result_op_queue['data_info'][0]) || !is_array($result_op_queue['data_info'][0]) || empty($result_op_queue['data_info'][0]))
            {
                $arr_log = array(
                    'nns_task_id' => $val['nns_id'],
                    'nns_state' => 'encode_error',
                    'nns_desc' => "查询nns_mgtvbk_op_queue队列无数据查询出来nns_id[{$val['nns_op_id']}]",
                    'nns_video_type' => $val['nns_video_type'],
                    'nns_video_id' => $val['nns_video_id'],
                    'nns_video_index_id' => $val['nns_video_index_id'],
                    'nns_org_id' => $this->op_sp,
                );
                nl_clip_task_log::add($this->dc, $arr_log);
                nl_clip_task::edit($this->dc, array('nns_state' => 'clip_encode_fail'), $val['nns_id']);
                continue;
            }

            $arr_path = (isset($result_op_queue['data_info'][0]['nns_ex_data']) && !empty($result_op_queue['data_info'][0]['nns_ex_data'])) ? json_decode($result_op_queue['data_info'][0]['nns_ex_data'], true) : null;
            $nns_path = (isset($arr_path['path']) && !empty($arr_path['path'])) ? $arr_path['path'] : '';
            $result_encode = $this->file_encode($val['nns_id'], $nns_path);
            if ($result_encode['ret'] != 0)
            {
                $this->error_info[] = $result_encode['reason'];
                $arr_log = array(
                    'nns_task_id' => $val['nns_id'],
                    'nns_state' => 'encode_error',
                    'nns_desc' => var_export($result_encode['reason'], true),
                    'nns_video_type' => $val['nns_video_type'],
                    'nns_video_id' => $val['nns_video_id'],
                    'nns_video_index_id' => $val['nns_video_index_id'],
                    'nns_org_id' => $this->op_sp,
                );
                nl_clip_task_log::add($this->dc, $arr_log);
            } else
            {
                nl_clip_task::edit($this->dc, array('nns_state' => 'clip_encode_loading'), $val['nns_id']);
                $arr_log = array(
                    'nns_task_id' => $val['nns_id'],
                    'nns_state' => 'encoding',
                    'nns_desc' => '正在转码',
                    'nns_video_type' => $val['nns_video_type'],
                    'nns_video_id' => $val['nns_video_id'],
                    'nns_video_index_id' => $val['nns_video_index_id'],
                    'nns_org_id' => $this->op_sp,
                );
                nl_op_queue::edit($this->dc, array('nns_encode_flag' => $result_encode['data_info']['key'], 'nns_status' => 8), $val['nns_op_id']);
                nl_clip_task_log::add($this->dc, $arr_log);
            }
        }
        var_dump($this->error_info);
        $arr_error_info = $this->error_info;
        $this->error_info = null;
        return $this->_return_result_data(0, var_export($arr_error_info, true));
    }

    /**
     * 文件转码队列删除
     * @param unknown $task_id
     */
    private function file_del($task_id)
    {
        $clip_file_encode_way = (isset($this->sp_config['clip_file_encode_way']) && strlen($this->sp_config['clip_file_encode_way']) > 0) ? strtolower($this->sp_config['clip_file_encode_way']) : '';
        switch ($clip_file_encode_way)
        {
            case 'post':
                $str_request_way = 'post';
                break;
            case 'get':
                $str_request_way = 'get';
                break;
            default:
                $str_request_way = 'post';
        }
        $obj_file_encode = new nl_file_encode($task_id, TMS_SYS_DEL_TASK);
        $data_file_encode = $obj_file_encode->task_distribute();
        if ($data_file_encode['ret'] != 0)
        {
            return $data_file_encode;
        }
        $obj_curl = new np_http_curl_class();
        $curl_data = $obj_curl->$str_request_way($this->sp_config['clip_file_encode_api_url'], $data_file_encode['data_info']);
        $curl_info = $obj_curl->curl_getinfo();
        $http_code = $curl_info['http_code'];
        if ($curl_info['http_code'] != '200')
        {
            return $this->_return_result_data(1, '[访问切片转码删除失败,CURL接口地址]：' . $this->sp_config['clip_file_encode_api_url'] . '[HTTP状态码]：' . $curl_info['http_code'] . '[HTTP错误]：' . $obj_curl->curl_error() . '；参数：' . var_export($data_file_encode['data_info'], true));
        }
        $curl_data = json_decode($curl_data, true);
        //成功
        if ($curl_data['code'] == '0')
        {
            return $this->_return_result_data(0, 'ok', $curl_data['info']);
        } else
        {
            return $this->_return_result_data(1, '[访问切片转码删除失败,CURL接口地址]：' . $this->sp_config['clip_file_encode_api_url'] . '[接口返回结果]：' . var_export($curl_data, true) . '；参数：' . var_export($data_file_encode['data_info'], true));
        }
    }

    /**
     * 获取文件转码状态
     * @param unknown $task_id
     */
    private function file_state($task_id, $api_url)
    {
        $clip_file_encode_way = (isset($this->sp_config['clip_file_encode_way']) && strlen($this->sp_config['clip_file_encode_way']) > 0) ? strtolower($this->sp_config['clip_file_encode_way']) : '';
        switch ($clip_file_encode_way)
        {
            case 'post':
                $str_request_way = 'post';
                break;
            case 'get':
                $str_request_way = 'get';
                break;
            default:
                $str_request_way = 'post';
        }
        $obj_file_encode = new nl_file_encode($task_id, TMS_SYS_GET_TASK_STATUS);
        $data_file_encode = $obj_file_encode->task_distribute();
        if ($data_file_encode['ret'] != 0)
        {
            return $data_file_encode;
        }
        $obj_curl = new np_http_curl_class();
        $curl_data = $obj_curl->$str_request_way($api_url, $data_file_encode['data_info']);
        $curl_info = $obj_curl->curl_getinfo();
        $http_code = $curl_info['http_code'];
        if ($curl_info['http_code'] != '200')
        {
            return $this->_return_result_data(1, '[访问切片转码状态失败,CURL接口地址]：' . $this->sp_config['clip_file_encode_api_url'] . '[HTTP状态码]：' . $curl_info['http_code'] . '[HTTP错误]：' . $obj_curl->curl_error(), '参数：' . var_export($data_file_encode['data_info'], true));
        }
        $curl_data = json_decode($curl_data, true);
        //成功
        if ($curl_data['code'] == '0')
        {
            return $this->_return_result_data(0, 'ok', $curl_data['info']);
        } else
        {
            return $this->_return_result_data(1, '[访问切片转码状态失败,CURL接口地址]：' . $this->sp_config['clip_file_encode_api_url'] . '[接口返回结果]：' . var_export($curl_data, true), '参数：' . var_export($data_file_encode['data_info'], true));
        }
    }

    /**
     * 转码设备负载均衡
     * @param unknown $result_queue
     * @param unknown $arr_file_encode_api_url
     */
    private function ex_load_balance($result_queue)
    {
        $result_queue = (isset($result_queue['data_info']) && !empty($result_queue['data_info']) && is_array($result_queue['data_info'])) ? $result_queue['data_info'] : null;
        $temp_queue_1 = $temp_queue = array();
        if (empty($this->sp_config_encode_url) || !is_array($this->sp_config_encode_url))
        {
            return $this->_return_result_data(1, '数据接口为空：' . var_export($this->sp_config_encode_url, true));
        }
        foreach ($this->sp_config_encode_url as $url_val)
        {
            $url_val = trim($url_val);
            $url_val_1 = md5($url_val);
            $temp_queue[$url_val_1] = 0;
            $temp_queue_1[$url_val_1] = $url_val;
        }
        if (is_array($result_queue) && !empty($result_queue))
        {
            foreach ($result_queue as $val)
            {
                if (isset($temp_queue[$val['nns_encode_flag']]))
                {
                    $temp_queue[$val['nns_encode_flag']] = $val['count'];
                }
            }
        }
        asort($temp_queue);
        $temp_queue = array_keys($temp_queue);
        if ($temp_queue === null || !is_array($temp_queue) || empty($temp_queue))
        {
            return $this->_return_result_data(1, '负载均衡错误：' . var_export($temp_queue, true));
        } else
        {
            return $this->_return_result_data(0, 'ok', array('key' => $temp_queue[0], 'val' => $temp_queue_1[$temp_queue[0]]));
        }
    }

    /**
     * 查询转码设备负载均衡
     * @param unknown $result_queue
     * @param unknown $arr_file_encode_api_url
     */
    private function query_load_balance()
    {
        if (empty($this->sp_config_encode_url) || !is_array($this->sp_config_encode_url))
        {
            return $this->_return_result_data(1, '数据接口为空：' . var_export($this->sp_config_encode_url, true));
        }
        $temp_queue = array();
        foreach ($this->sp_config_encode_url as $url_val)
        {
            $url_val = trim($url_val);
            $url_val_1 = md5($url_val);
            $temp_queue[$url_val_1] = $url_val;
        }
        return $this->_return_result_data(0, 'ok', $temp_queue);
    }


    /**
     * 文件转码
     * @param unknown $task_id
     * @param unknown $nns_path
     */
    private function file_encode($task_id, $nns_path)
    {
        if (!isset($this->sp_config['clip_file_addr_input']) || strlen($this->sp_config['clip_file_addr_input']) < 1)
        {
            return $this->_return_result_data(1, '切片文件输入为空:' . $this->sp_config['clip_file_addr_input']);
        }
        if (!isset($this->sp_config['clip_file_addr_output']) || strlen($this->sp_config['clip_file_addr_output']) < 1)
        {
            return $this->_return_result_data(1, '切片文件输出为空:' . $this->sp_config['clip_file_addr_output']);
        }
        $result_queue = nl_op_queue::query_group_encode_flag($this->dc, $this->op_sp);
        if ($result_queue['ret'] != 0)
        {
            return $result_queue;
        }
        $result_load_balance = $this->ex_load_balance($result_queue);
        if ($result_load_balance['ret'] != 0)
        {
            return $result_load_balance;
        }
        $clip_file_encode_way = (isset($this->sp_config['clip_file_encode_way']) && strlen($this->sp_config['clip_file_encode_way']) > 0) ? strtolower($this->sp_config['clip_file_encode_way']) : '';
        switch ($clip_file_encode_way)
        {
            case 'post':
                $str_request_way = 'post';
                break;
            case 'get':
                $str_request_way = 'get';
                break;
            default:
                $str_request_way = 'post';
        }
        $ftp_in = rtrim($this->sp_config['clip_file_addr_input'], '/') . '/' . ltrim($nns_path, '/');
        $ftp_out = $this->sp_config['clip_file_addr_output'];
        //拆分FTP地址  输入
        $url_arr_in = parse_url($ftp_in);
        $user_in = (isset($url_arr_in["user"]) && strlen($url_arr_in["user"]) > 0) ? $url_arr_in["user"] : '';
        $pass_in = (isset($url_arr_in["pass"]) && strlen($url_arr_in["pass"]) > 0) ? $url_arr_in["pass"] : '';
        $path_in = (isset($url_arr_in["path"]) && strlen($url_arr_in["path"]) > 0) ? $url_arr_in["path"] : '';

        //拆分FTP地址  输出
        $url_arr_out = parse_url($ftp_out);
        $host_out = (isset($url_arr_out["host"]) && strlen($url_arr_out["host"]) > 0) ? $url_arr_out["host"] : '';
        $user_out = (isset($url_arr_out["user"]) && strlen($url_arr_out["user"]) > 0) ? $url_arr_out["user"] : '';
        $pass_out = (isset($url_arr_out["pass"]) && strlen($url_arr_out["pass"]) > 0) ? $url_arr_out["pass"] : '';
        $path_out = (isset($url_arr_out["path"]) && strlen($url_arr_out["path"]) > 0) ? $url_arr_out["path"] : '';
        $port_out = (isset($url_arr_out["port"]) && strlen($url_arr_out["port"]) > 0) ? $url_arr_out["port"] : 21;
        $obj_ftp = new nl_ftp($host_out, $user_out, $pass_out, $port_out);
        $path_out = trim(trim($path_out, '/'));
        $path_base = (strlen($path_out) > 0) ? $path_out : '';
        $arr_path_info = pathinfo($path_in);
        if (isset($arr_path_info['dirname']))
        {
            $arr_path_info['dirname'] = trim($arr_path_info['dirname'], '/');
            if (strlen($arr_path_info['dirname']))
            {
                $path_base .= '/' . $arr_path_info['dirname'];
            }
        }
        $path_base = trim($path_base, '/');
        $obj_ftp = new nl_ftp($host_out, $user_out, $pass_out, $port_out);
        $result_ftp = $obj_ftp->make_dir($path_base);
        if ($result_ftp['ret'] != 0)
        {
            return $result_ftp;
        }
        $str_ftp_url = "ftp://";
        if (strlen($user_out) > 0 && strlen($pass_out) > 0)
        {
            $str_ftp_url .= "{$user_out}:{$pass_out}@";
        }
        $str_ftp_url .= "{$host_out}:{$port_out}/{$path_base}/{$arr_path_info['filename']}";
        $arr_inout_put = array(
            'input' => array(
                'user' => $user_in,
                'pwd' => $pass_in,
                'path' => $ftp_in,
            ),
            'output' => array(
                'user' => $user_out,
                'pwd' => $pass_out,
                'path' => $str_ftp_url,
            ),
        );
        $obj_file_encode = new nl_file_encode($task_id, TMS_SYS_SET_TASK, $arr_inout_put);
        $data_file_encode = $obj_file_encode->task_distribute();
        if ($data_file_encode['ret'] != 0)
        {
            return $data_file_encode;
        }
        $obj_curl = new np_http_curl_class();
        $curl_data = $obj_curl->$str_request_way($result_load_balance['data_info']['val'], $data_file_encode['data_info']);
        $curl_info = $obj_curl->curl_getinfo();
        $http_code = $curl_info['http_code'];
        if ($curl_info['http_code'] != '200')
        {
            return $this->_return_result_data(1, '[访问切片转码失败,CURL接口地址]：' . $this->sp_config['clip_file_encode_api_url'] . '[HTTP状态码]：' . $curl_info['http_code'] . '[HTTP错误]：' . $obj_curl->curl_error(), '参数：' . var_export($data_file_encode['data_info'], true));
        }
// 	    $curl_data = json_decode($curl_data,true);
        $curl_data = trim($curl_data);
        unset($obj_curl);
        //成功
        if ($curl_data == '0')
        {
            return $this->_return_result_data(0, '[访问切片转码成功,CURL接口地址]：' . $this->sp_config['clip_file_encode_api_url'], $result_load_balance['data_info']);
        } else
        {
            return $this->_return_result_data(1, '[访问切片转码失败,CURL接口地址]：' . $this->sp_config['clip_file_encode_api_url'] . '[接口返回结果]：' . var_export($curl_data, true), '参数：' . var_export($data_file_encode['data_info'], true));
        }
    }

    /**
     * 数据输出
     * @param unknown $ret
     * @param unknown $reason
     * @param string $data_info
     */
    private function _return_result_data($ret, $reason, $data_info = null)
    {
        return array(
            'ret' => $ret,
            'reason' => $reason,
            'data_info' => $data_info
        );
    }

    private function __filter_blacklist($sp_id, $type, $id)
    {
//		STEP1 如果是type不是video的话，通过ID反查主媒资ID
//		如果TYPE INDEX  nns_vod_index  nns_vod_id
//		如果TYPE MEDIA  nns_vod_media  nns_vod_id


//		STEP2 通过黑名单针对SP来筛选 返回TRUE或FALSE 如为FALSE就跳过
    }

    /**
     * 添加消息分组
     * @param unknown $dc
     * @param unknown $params
     */
    public function add_group_message($dc, $params)
    {
        $need_del = false;
        // 节约数据库的cp查询 如果存在了直接取值
        if (!isset($this->arr_cp_config[$params['cp_id']]['message_group_enabled']))
        {
            $result_cp = nl_cp::query_by_id($dc, $params['cp_id']);
            $result_cp = (isset($result_cp['data_info']['nns_config']) && !empty($result_cp['data_info'])) ? json_decode($result_cp['data_info']['nns_config'], true) : null;
            if (!isset($result_cp['message_group_enabled']) || $result_cp['message_group_enabled'] != 1)
            {
                $this->arr_cp_config[$params['cp_id']]['message_group_enabled'] = 0;
                return $result_cp;
            }
            $this->arr_cp_config[$params['cp_id']]['message_group_enabled'] = $result_cp['message_group_enabled'];
        } else
        {
            if (!isset($this->arr_cp_config[$params['cp_id']]['message_group_enabled']) || $this->arr_cp_config[$params['cp_id']]['message_group_enabled'] != 1)
            {
                return array(
                    'ret' => 0,
                    'reason' => 'ok',
                    'data_info' => array('need_del' => $need_del),
                );
            }
        }
        //查询上游接收的消息队列数据信息
        $result_message = nl_message::query_message_by_message_id($dc, $params['message_id'], $params['cp_id']);
        if ($result_message['ret'] != 0 || !isset($result_message['data_info']) || empty($result_message['data_info']))
        {
            return $result_message;
        }
        //xml 内容 总共数据多少组
        $total_num = $result_message['data_info']['nns_content_number'];
        //查询此分组是否存在，如果不存在添加  状态默认为 0 收集分组消息
        $result_message_group = nl_message_group::query_by_cp_message_id($dc, $params['cp_id'], $params['message_id'], $params['sp_id']);
        if ($result_message_group['ret'] != 0)
        {
            return $result_message_group;
        }
        $str_guid = np_guid_rand();
        if (!isset($result_message_group['data_info']) || empty($result_message_group['data_info']))
        {
            $arr_message_group = array(
                'nns_id' => $str_guid,
                'nns_message_guid' => $result_message['data_info']['nns_id'],
                'nns_message_id' => $params['message_id'],
                'nns_cp_id' => $params['cp_id'],
                'nns_sp_id' => $params['sp_id'],
                'nns_state' => 0,
            );
            $result_group_add = nl_message_group::add($dc, $arr_message_group);
            if ($result_group_add['ret'] != 0)
            {
                return $result_group_add;
            }
        } else
        {
            $str_guid = $result_message_group['data_info']['nns_id'];
            if ($result_message_group['data_info']['nns_state'] != 0)
            {
                $result_group_edit = nl_message_group::edit($dc, array('nns_state' => 0), $str_guid);
                if ($result_group_edit['ret'] != 0)
                {
                    return $result_group_edit;
                }
            }
        }
        //查询分组 已经收集了多少条数据了
        $result_group_list_count = nl_message_group_list::query_group_count($dc, $str_guid);
        if ($result_group_list_count['ret'] != 0)
        {
            return $result_group_list_count;
        }
        $result_message_group_list = nl_message_group_list::query_by_video_message_id($dc, $params['video_id'], $str_guid);
        if ($result_message_group_list['ret'] != 0)
        {
            return $result_message_group_list;
        }
        if (!isset($result_message_group_list['data_info']) || empty($result_message_group_list['data_info']))
        {
            //如果数据是添加  分组数据+1
            $result_group_list_count['data_info']++;
            $arr_message_group_list = array(
                'nns_message_group_id' => $str_guid,
                'nns_type' => $params['type'],
                'nns_import_id' => $params['import_id'],
                'nns_video_id' => $params['video_id'],
                'nns_ext_url' => $params['nns_ext_url'],
                'nns_desc' => '',
                'nns_state' => 0,
            );
            if (in_array($params['type'], array('video', 'index', 'live', 'live_index')))
            {
                $need_del = true;
                $arr_message_group_list['nns_state'] = 1;
                $arr_message_group_list['nns_desc'] = $params['type'] . " import ok";
            }
            $result_group_list_add = nl_message_group_list::add($dc, $arr_message_group_list);
            if ($result_group_list_add['ret'] != 0)
            {
                return $result_group_list_add;
            }
        } else
        {
            $arr_message_group_list_edit['nns_state'] = 0;
            if (in_array($params['type'], array('video', 'index', 'live', 'live_index')))
            {
                $need_del = true;
                $arr_message_group_list_edit['nns_state'] = 1;
                $arr_message_group_list_edit['nns_desc'] = $params['type'] . " import ok";
                $arr_message_group_list_edit['nns_ext_url'] = $params['nns_ext_url'];
            }
            $result_group_list_edit = nl_message_group_list::edit($dc, $arr_message_group_list_edit, $result_message_group_list['data_info']['nns_id']);
            if ($result_group_list_edit['ret'] != 0)
            {
                return $result_group_list_edit;
            }
        }
        //检查收集的分组信息  是否和 原始接收的数据条数一致   如果一致改变状态置为  数据接收完毕  1
        if ($result_group_list_count['data_info'] >= $total_num)
        {
            $result_group_edit = nl_message_group::edit($dc, array('nns_state' => 1), $str_guid);
            if ($result_group_edit['ret'] != 0)
            {
                return $result_group_edit;
            }
        }
        return array(
            'ret' => 0,
            'reason' => 'ok',
            'data_info' => array('need_del' => $need_del),
        );
    }


    /**
     * 添加任务列队
     * @param video_id string
     * @param video_type string
     * @param action
     * @param sp_id string
     * @param $old_media_id string
     * @param is_bool  false 不是存量任务     true  存量任务
     */

    public function q_add_task($video_id, $video_type, $action, $sp_id = null, $old_media_id = null, $is_bool = false, $message_id = null, $nns_id = null, $nns_weight = 0, $nns_is_group = 0, $sp_config)
    {
        set_time_limit(0);
        $dc = nl_get_dc(array(
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $dc->open();
        $db = $dc->db();
        $nns_weight = (int)$nns_weight;
        $nns_weight = $nns_weight > 0 ? $nns_weight : 0;
        //获取任务名称
        $task_arr = $this->get_task_name($video_id, $video_type);
        $task_name = $task_arr['task_name'];
        $asset_id = $task_arr['asset_id'];
        //码率
        $nns_kbps = $task_arr['nns_kbps'];
        $nns_media_encode_flag = (isset($task_arr['nns_media_encode_flag']) && $task_arr['nns_media_encode_flag'] == '1') ? 1 : 0;
        $nns_media_encode_flag = (isset($task_arr['nns_media_encode_flag']) && $task_arr['nns_media_encode_flag'] == '1') ? 1 : 0;
        $category_id = $this->get_category_by_video_id($db, $asset_id);
        $params = array(
            'ex_id' => $video_id,
            'type' => $video_type,
            'action' => $action,
            'nns_kbps' => $nns_kbps,
            'name' => $task_name,
            'id' => $nns_id,
            'weight' => $nns_weight,
            'nns_is_group' => $nns_is_group,
            'nns_media_encode_flag' => $nns_media_encode_flag,
            'nns_ext_info' => isset($task_arr['nns_ext_info']) ? $task_arr['nns_ext_info'] : '',
            'nns_cp_id' => isset($task_arr['cp_id']) ? $task_arr['cp_id'] : '',
            'nns_url' => isset($task_arr['nns_url']) ? $task_arr['nns_url'] : '',
            'nns_live_to_media' => isset($task_arr['nns_live_to_media']) ? $task_arr['nns_live_to_media'] : '1',
        );
        if (strlen($message_id) > 0)
        {
            $params['message_id'] = $message_id;
        }
        if (isset($sp_config['op_queue_model']) && $sp_config['op_queue_model'] == 1 && $nns_is_group == 1 && strlen($message_id) > 0)
        {
            $arr_message_group = array(
                'message_id' => $message_id,
                'cp_id' => $task_arr['cp_id'],
                'sp_id' => $sp_id,
                'type' => $video_type,
                'import_id' => $task_arr['import_id'],
                'video_id' => $video_id,
                'nns_ext_url' => $task_arr['nns_ext_url'],
            );
            $result_ex = $this->add_group_message($dc, $arr_message_group);
            if ($result_ex['ret'] != 0)
            {
                return $result_ex;
            }
            if (isset($result_ex['data_info']['need_del']) && $result_ex['data_info']['need_del'] === true)
            {
                return true;
            }
        }

        //print_r($params);die;
        //if(empty($task_name)){
        //	return ;
        //}
        $sp_list = sp_model::get_sp_list($sp_id);
        // $sp_list_sql = "select * from nns_mgtvbk_sp";
        // $sp_list = nl_db_get_all($sp_list_sql, $db);
        foreach ($sp_list as $sp)
        {
            $sp_config = json_decode($sp['nns_config'], true);
            //判断是否清理消息ID为空的任务
            if (isset($sp_config['import_task_clear']) && (int)$sp_config['import_task_clear'] === 1 && !isset($params['message_id']))
            {
                continue;
            }


            //中心注入主令开关，如果关闭了，则排除掉该Sp
            if (isset($sp_config['op_queue_enabled']) && $sp_config['op_queue_enabled'] == '0')
            {
                if (!isset($sp_config['before_execute_sp']) || empty($sp_config['before_execute_sp']))
                {
                    continue;
                }
                //获取前置cdn 配置
                $before_sp_list = sp_model::get_sp_list($sp_config['before_execute_sp']);
                $before_sp_config = json_decode($before_sp_list[0]['nns_config'], true);
                if (!isset($before_sp_config['after_execute_sp']) || $before_sp_config['after_execute_sp'] != $sp_id)
                {
                    continue;
                }
            }

            $ratebit_start_kbps = '';
            $ratebit_end_kbps = '';
            //查看码率开关是否开启，开启了处理码率控制逻辑，关闭直接通过
            if ($video_type == 'media' && isset($sp_config['import_ratebit_enabled']) && $sp_config['import_ratebit_enabled'] == '1' && isset($sp_config['import_ratebit_start']) && isset($sp_config['import_ratebit_end']))
            {
                $ratebit_flag_start = (strlen($sp_config['import_ratebit_start']) < 1 || (strlen($sp_config['import_ratebit_start']) > 0 && $nns_kbps >= $sp_config['import_ratebit_start'])) ? true : false;
                $ratebit_flag_end = (strlen($sp_config['import_ratebit_end']) < 1 || (strlen($sp_config['import_ratebit_end']) > 0 && $nns_kbps <= $sp_config['import_ratebit_end'])) ? true : false;
                $ratebit_start_kbps = (strlen($sp_config['import_ratebit_start']) > 0 && (int)$sp_config['import_ratebit_start'] > 0) ? (int)$sp_config['import_ratebit_start'] : '';
                $ratebit_end_kbps = (strlen($sp_config['import_ratebit_end']) > 0 && (int)$sp_config['import_ratebit_end'] > 0) ? (int)$sp_config['import_ratebit_end'] : '';
                if (!$ratebit_flag_start || !$ratebit_flag_end)
                {
                    continue;
                }
            }
            //判断黑名单or白名单
            //判读视频是否是黑名单
            $black_data = $this->__get_is_black($sp['nns_id'], 1, $asset_id);
            //判断栏目是否是黑名单
            $black_category_data = $this->__get_is_black($sp['nns_id'], 1, null, $category_id);
            if (is_array($black_data[0]) || !empty($black_data[0]) || is_array($black_category_data[0]) || !empty($black_category_data[0]))
            {
                continue;
            }
            //判断栏目是否是白名单
            $black_category_data_true = $this->__get_is_black($sp['nns_id'], 0, null, $category_id);
            if (is_array($black_category_data_true) && count($black_category_data_true) > 0)
            {
                foreach ($black_category_data_true as $bval)
                {
                    if ($bval['nns_org_id'] == $sp['nns_id'])
                    {
                        $black_bool = true;
                        break;
                    } else
                    {
                        $black_bool = false;
                    }
                }
            } else
            {
                $black_bool = true;
            }
            //判断视频是否白名单
            $black_data_true = $this->__get_is_black($sp['nns_id'], 0, $asset_id);
            $black_bool = true;
            //print_r($black_data_true);die;
            if (is_array($black_data_true) && count($black_data_true) > 0)
            {
                foreach ($black_data_true as $bval)
                {
                    if ($bval['nns_video_id'] == $asset_id && $bval['nns_org_id'] == $sp['nns_id'])
                    {
                        $black_bool = true;
                        break;
                    } else
                    {
                        $black_bool = false;
                    }
                }
            } else
            {
                $black_bool = true;
            }

            if ($black_bool === false)
            {
                continue;
            }
            //if($params['org_id']!='sihua'){
            //	continue;
            //}
            $params['org_id'] = $sp['nns_id'];
            //生成任务
            //关闭注入
            if ($is_bool === false)
            {
                if (isset($sp_config['disabled_sp_queue']) && (int)$sp_config['disabled_sp_queue'] === 1 && $action != BK_OP_DELETE)
                {
                    continue;
                }
            }


            //如果是混合模式就删除原来的，添加新的码率最高的
            //i_write_log_core(var_export($params,true),'q_add_task/'.$sp['nns_id']);
            if (isset($sp_config['cdn_import_media_mode']) && ((int)$sp_config['cdn_import_media_mode'] === 1 || (int)$sp_config['cdn_import_media_mode'] === 2) && $video_type == BK_OP_MEDIA)
            {
                $video_media_info = video_model::get_vod_media_info($video_id);

                //新增码率控制模式  预防同个片注入不同sp 出现的码率混乱  （例如：A sp 为混合模式又加了码率控制  要在 码率控制的范围内做筛选，不能超出码率控制范围）  liangpan 2016-03-23
                $temp_str_where_and = '';
                if (strlen($ratebit_start_kbps) > 0)
                {
                    $temp_str_where_and .= " and nns_kbps >='{$ratebit_start_kbps}' ";
                }
                if (strlen($ratebit_end_kbps) > 0)
                {
                    $temp_str_where_and .= " and nns_kbps <='{$ratebit_end_kbps}' ";
                }
                $sql = "select * from nns_vod_media where nns_vod_index_id='{$video_media_info['nns_vod_index_id']}' {$temp_str_where_and} and nns_deleted!=1 and nns_media_service='{$video_media_info['nns_media_service']}' order by nns_kbps desc limit 1";
                $new_media_info = nl_db_get_one($sql, $db);
                if (is_array($new_media_info))
                {
                    //add
                    $task_arr = $this->get_task_name($new_media_info['nns_id'], $video_type);
                    $params['ex_id'] = $new_media_info['nns_id'];
                    $params['action'] = BK_OP_ADD;
                    $params['name'] = $task_arr['task_name'];
                    if ($params['ex_id'])
                    {
                        if ($is_bool === true)
                        {
                            if (isset($sp_config['sp_default_weight']) && (int)$sp_config['sp_default_weight'] > 0)
                            {
                                $params['weight'] = $sp_config['sp_default_weight'];
                            }

                        }

                        $re = $this->op_queue->add($db, $params);
                    }
                }
                if (!empty($old_media_id) && $old_media_id != $new_media_info['nns_id'])
                {
                    $task_arr = $this->get_task_name($old_media_id, $video_type);
                    $params['ex_id'] = $old_media_id;
                    $params['action'] = BK_OP_DELETE;
                    $params['name'] = $task_arr['task_name'];
                    if ($params['ex_id'])
                    {
                        if ($is_bool === true)
                        {
                            if (isset($sp_config['sp_default_weight']) && (int)$sp_config['sp_default_weight'] > 0)
                            {
                                $params['weight'] = $sp_config['sp_default_weight'];
                            }

                        }

                        $re = $this->op_queue->add($db, $params);
                    }
                }

                if (is_array($video_media_info))
                {
                    if ($action == BK_OP_DELETE)
                    {
                        $task_arr = $this->get_task_name($old_media_id, $video_type);
                        $params['ex_id'] = $old_media_id;
                        $params['action'] = BK_OP_DELETE;
                        $params['name'] = $task_arr['task_name'];
                        if ($params['ex_id'])
                        {
                            if ($is_bool === true)
                            {
                                if (isset($sp_config['sp_default_weight']) && (int)$sp_config['sp_default_weight'] > 0)
                                {
                                    $params['weight'] = $sp_config['sp_default_weight'];
                                }

                            }

                            $re = $this->op_queue->add($db, $params);
                        }
                    }
                }
            } else
            {
                if ($params['ex_id'])
                {
                    if ($is_bool === true)
                    {
                        if (isset($sp_config['sp_default_weight']) && (int)$sp_config['sp_default_weight'] > 0)
                        {
                            $params['weight'] = $sp_config['sp_default_weight'];
                        }

                    }

                    $re = $this->op_queue->add($db, $params);
                }
            }

            //print_r($params);
            i_write_log_core(var_export($params, true), 'q_add_task/' . $sp['nns_id']);
            //if($re['state']!=100){

            //i_write_log_core(var_export($params,true),'q_add_task/'.$sp['nns_id']);
            //}
            unset($sp_config);
            usleep(1000);
        }
        unset($db);
        return true;
    }


    /**
     * 获取sql
     * @param string $sp_id 运营商ID
     * @param string $video_type 点播类型:video,index,media
     * @param bool $is_cdn_resend 是否是CDN重发,CDN重发的时候只查询执行失败的
     */
    public function get_cdn_sql($sp_id, $video_type, $is_cdn_resend, $sp_config = null)
    {
        set_time_limit(0);
        if (!isset($sp_config) || !is_array($sp_config) || empty($sp_config))
        {
            $sp_info = sp_model::get_sp_info($sp_id);
            $sp_config = json_decode($sp_info['nns_config'], true);//获取sp的策略
        }
        $sql = "select t1.* from nns_mgtvbk_c2_task t1 where t1.nns_org_id='$sp_id'";
        $where_array = array();
        $ext_sql = '';
        $cdn_video_max = 'cdn_' . strtolower($video_type) . '_max';
        $limit = (isset($sp_config[$cdn_video_max]) && (int)$sp_config[$cdn_video_max] > 0) ? (int)$sp_config[$cdn_video_max] : 100;
        //重发的时候限制下重发总条数
        $limit = $is_cdn_resend ? ceil($limit / 3) : $limit;
        switch ($video_type)
        {
            case BK_OP_VIDEO:
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_VIDEO, BK_OP_ADD, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_VIDEO, BK_OP_MODIFY, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_VIDEO, BK_OP_DELETE, $is_cdn_resend);
                break;
            case BK_OP_INDEX:
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_INDEX, BK_OP_ADD, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_INDEX, BK_OP_MODIFY, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_INDEX, BK_OP_DELETE, $is_cdn_resend);

                //判断父级是否需要注入CDN
                $parent_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_VIDEO, BK_OP_ADD, $is_cdn_resend);
                $parent_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_VIDEO, BK_OP_ADD, $is_cdn_resend);
                $parent_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_VIDEO, BK_OP_ADD, $is_cdn_resend);

                $nns_status = '';
                if (is_array(array_filter($parent_array)) && count(array_filter($parent_array)) > 0)
                {
                    $nns_status = $is_cdn_resend ? ' and t2.nns_status=-1 ' : ' and t2.nns_status=0 ';
                }
                if ( !in_array($sp_id, array('kukai')))
                {
                    $ext_sql = " and  (t1.nns_action='" . BK_OP_DELETE . "' or exists (select 1 from nns_mgtvbk_c2_task t2 where t2.nns_org_id='$sp_id' and t1.nns_src_id=t2.nns_ref_id $nns_status and t2.nns_type='" . BK_OP_VIDEO . "'))";
                }
                break;
            case BK_OP_MEDIA:
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_MEDIA, BK_OP_ADD, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_MEDIA, BK_OP_MODIFY, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_MEDIA, BK_OP_DELETE, $is_cdn_resend);

                $parent_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_INDEX, BK_OP_ADD, $is_cdn_resend);
                $parent_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_INDEX, BK_OP_ADD, $is_cdn_resend);
                $parent_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_INDEX, BK_OP_ADD, $is_cdn_resend);

                $nns_status = '';
                if (is_array(array_filter($parent_array)) && count(array_filter($parent_array)) > 0)
                {
                    $nns_status = $is_cdn_resend ? ' and t2.nns_status=-1 ' : ' and t2.nns_status=0 ';
                }

                if ( !in_array($sp_id, array('suzhou_4k','jscn_sihua_vod')))
                {
                    $ext_sql = " and (t1.nns_action='" . BK_OP_DELETE . "' or exists (select 1 from nns_mgtvbk_c2_task t2 where t2.nns_org_id='$sp_id'  and t1.nns_src_id=t2.nns_ref_id $nns_status and t2.nns_type='" . BK_OP_INDEX . "'))";
                }
                break;
            case BK_OP_LIVE:
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_LIVE, BK_OP_ADD, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_LIVE, BK_OP_MODIFY, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_LIVE, BK_OP_DELETE, $is_cdn_resend);
                break;
            case BK_OP_LIVE_MEDIA:
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_LIVE_MEDIA, BK_OP_ADD, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_LIVE_MEDIA, BK_OP_MODIFY, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_LIVE_MEDIA, BK_OP_DELETE, $is_cdn_resend);
                break;
            case BK_OP_PLAYBILL:
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_PLAYBILL, BK_OP_ADD, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_PLAYBILL, BK_OP_MODIFY, $is_cdn_resend);
                $where_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_PLAYBILL, BK_OP_DELETE, $is_cdn_resend);

                $parent_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_LIVE_MEDIA, BK_OP_ADD, $is_cdn_resend);
                $parent_array[] = $this->__get_child_cdn_sql($sp_config, BK_OP_LIVE_MEDIA, BK_OP_MODIFY, $is_cdn_resend);
                $nns_status = '';
                if (is_array(array_filter($parent_array)) && count(array_filter($parent_array)) > 0)
                {
                    $nns_status = $is_cdn_resend ? ' and t2.nns_status=-1 ' : ' and t2.nns_status=0 ';
                }

                /**
                 * 除黑龙江电信注入中兴CDN外，都需要检查直播片源是否已注入
                 * @author chunyang.shu
                 * @date 2017-10-26
                 */
                if ( !in_array($sp_id, array('hljdx', 'hljdx_hw','jscn_sihua_vod')))
                {
                    $ext_sql = " and  (t1.nns_action='" . BK_OP_DELETE . "' or exists (select 1 from nns_mgtvbk_c2_task t2 where t2.nns_org_id='$sp_id' and t1.nns_src_id=t2.nns_ref_id $nns_status and t2.nns_type='" . BK_OP_LIVE_MEDIA . "'))";
                }

                break;
            default:
                return null;
        }
        if (is_array(array_filter($where_array)) && count(array_filter($where_array)) > 0)
        {
            $sql .= ' and (' . implode(array_filter($where_array), ' or ') . ') ';
        } else
        {
            return null;
        }

        $sql .= $ext_sql;
        if (isset($sp_config[$video_type]['enabled']) && $sp_config[$video_type]['enabled'] == '1')
        {
            $sql .= ' group by t1.nns_src_id ';
        }
        $sql .= ' order by t1.nns_modify_time asc limit  ' . $limit;

        return $sql;
    }

    private function __get_child_cdn_sql($config, $type, $action, $is_cdn_resend)
    {
        set_time_limit(0);
        //获取策略
        $config_action = $config[$type . '_' . $action];
        //优先级  0或不设为优先执行CDN注入，再执行EPG注入，1为优先执行EPG注入，再执行CDN注入
        if ((int)$config_action['status'] === 2)
        {
            return null;
        }
        //-->start	添加注入失败次数判定 xingcheng.hu
        $retry_time = (isset($config['cdn_fail_retry_time']) && strlen($config['cdn_fail_retry_time']) > 0 && isset($config['cdn_fail_retry_mode']) && $config['cdn_fail_retry_mode'] == '0') ? $config['cdn_fail_retry_time'] : null;
        $ext_sql = ($retry_time !== null) ? "and t1.nns_cdn_fail_time <= $retry_time" : null;
        //<--end
        $nns_status = $is_cdn_resend ? 't1.nns_status=-1' : 't1.nns_status=1';
        if ((int)$config_action['priority'] === 0)
        {
            //0为注入CDN和EPG，1为注入CDN，2为注入EPG
            return "(t1.nns_type='$type' and t1.nns_action='$action' and $nns_status " . "$ext_sql)";
        } elseif ((int)$config_action['priority'] === 1 && (int)$config_action['status'] === 0)
        {
            //0为注入CDN和EPG，1为注入CDN，2为注入EPG
            return "(t1.nns_type='$type' and t1.nns_action='$action' and $nns_status and t1.nns_epg_status=99 " . "$ext_sql)";
        }
        return null;
    }

    /**
     * @desc 获取sql
     * @param sp_id
     * @param type
     *
     */
    public function get_epg_sql($sp_id, $video_type)
    {
        set_time_limit(0);
        $sp_info = sp_model::get_sp_info($sp_id);
        $sp_config = json_decode($sp_info['nns_config'], true);//获取sp的策略
        $sql = "select t1.* from nns_mgtvbk_c2_task t1 where t1.nns_org_id='$sp_id'";
        $where_array = array();
        $ext_sql = '';
        $limit = 0;
        switch ($video_type)
        {
            case BK_OP_VIDEO:
                //$add_config_video = $sp_config[SP_CONFIG_VIDEO_ADD];//添加操作的策略
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_VIDEO, BK_OP_ADD);
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_VIDEO, BK_OP_MODIFY);
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_VIDEO, BK_OP_DELETE);
                break;
            case BK_OP_INDEX:
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_INDEX, BK_OP_ADD);
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_INDEX, BK_OP_MODIFY);
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_INDEX, BK_OP_DELETE);

                $ext_sql = " and  (t1.nns_action='" . BK_OP_DELETE . "' or exists (select 1 from nns_mgtvbk_c2_task t2 where t2.nns_org_id='$sp_id'  and t1.nns_src_id=t2.nns_ref_id and t2.nns_epg_status=99 and t2.nns_type='" . BK_OP_VIDEO . "'))";
                break;
            case BK_OP_MEDIA:
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_MEDIA, BK_OP_ADD);
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_MEDIA, BK_OP_MODIFY);
                $where_array[] = $this->__get_child_epg_sql($sp_config, BK_OP_MEDIA, BK_OP_DELETE);
                if ( !in_array($sp_id, array('cbczq_zte')))
                {
                    $ext_sql = " and (t1.nns_action='" . BK_OP_DELETE . "' or exists (select 1 from nns_mgtvbk_c2_task t2 where t2.nns_org_id='$sp_id'  and t1.nns_src_id=t2.nns_ref_id and t2.nns_epg_status in (99) and t2.nns_type='" . BK_OP_INDEX . "'))";
                }
                break;
            case 'live':
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_ADD);
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_MODIFY);
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_DELETE);
                break;
            case 'live_media':
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_ADD);
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_MODIFY);
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_DELETE);
                break;
            case 'playbill':
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_ADD);
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_MODIFY);
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_DELETE);
                break;
            case 'product':
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_ADD);
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_MODIFY);
                $where_array[] = $this->__get_child_epg_sql($sp_config, $video_type, BK_OP_DELETE);
                break;
        }
        if (is_array(array_filter($where_array)) && count(array_filter($where_array)) > 0)
        {
            $sql .= ' and (' . implode(array_filter($where_array), ' or ') . ') ';
        } else
        {
            return null;
        }
        $sql .= $ext_sql;
// 		var_dump($sql);die;

        if (isset($sp_config['epg_pre_max']))
        {
            $limit = $sp_config['epg_pre_max'];
        } else
        {
            $limit = 100;
        }
        $sql .= $ext_sql;
        if (isset($sp_config[$video_type]['enabled']) && $sp_config[$video_type]['enabled'] == '1')
        {
            $sql .= ' group by t1.nns_src_id ';
        }
        $sql .= ' order by t1.nns_modify_time asc  limit ' . $limit;
        return $sql;
    }

    private function __get_child_epg_sql($config, $type, $action)
    {
        set_time_limit(0);
        //获取策略
        $config_action = $config[$type . '_' . $action];
        //最终状态是1的排除
        if ((int)$config_action['status'] === 1)
        {
            return null;
        }
        //-->start	添加注入失败次数判定 xingcheng.hu
        $retry_time = (isset($config_action['retry_time']) && strlen($config_action['retry_time']) > 0) ? $config_action['retry_time'] : null;
        $ext_sql = ($retry_time !== null) ? "and t1.nns_epg_fail_time <= $retry_time" : null;
        //<--end
        //CDN优先
        if ((int)$config_action['priority'] === 0)
        {
            //0为注入CDN和EPG，1为注入CDN，2为注入EPG
            if ((int)$config_action['status'] === 0)
            {
                return "(t1.nns_type='$type'  and t1.nns_action='$action'  and t1.nns_status=0  and t1.nns_epg_status=97 " . "$ext_sql)";
            } elseif ((int)$config_action['status'] === 2)
            {
                return "(t1.nns_type='$type'  and t1.nns_action='$action'   and t1.nns_epg_status=97 " . "$ext_sql)";
            }
        } elseif ((int)$config_action['priority'] === 1)
        {
            //0为注入CDN和EPG，1为注入CDN，2为注入EPG
            return "(t1.nns_type='$type'  and t1.nns_action='$action'  and t1.nns_epg_status=97 " . "$ext_sql)";
        }
        return null;
    }

    /**
     * @desc 获取列队的记录
     */
    public function get_q_task_list($sp_id, $filter = null, $start = 0, $size = 100)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_READ);
        $sql = "select * " .
            "from nns_mgtvbk_op_queue  where nns_org_id='$sp_id'";
        if ($filter != null)
        {
            $wh_arr = array();
            if (!empty($filter['nns_name']))
            {
                $wh_arr[] = " nns_name like '%" . $filter['nns_name'] . "%'";
            }
            if (!empty($filter['day_picker_start']))
            {
                $wh_arr[] = " nns_create_time>='" . $filter['day_picker_start'] . "'";
            }
            if (!empty($filter['day_picker_end']))
            {
                $wh_arr[] = " nns_create_time<='" . $filter['day_picker_end'] . "'";
            }
            if (!empty($filter['nns_type']))
            {
                $wh_arr[] = " nns_type='" . $filter['nns_type'] . "'";
            }
            if (!empty($filter['nns_action']))
            {
                $wh_arr[] = " nns_action='" . $filter['nns_action'] . "'";
            }
            if (!empty($filter['nns_state']))
            {
                $state = $filter['nns_state'];
                switch ($state)
                {
                    case 'bk_content_wait':
                        $wh_arr[] = " nns_status=" . BK_OP_WAIT;
                        break;
                    case 'bk_content_clip_doing':
                        $wh_arr[] = " nns_status=" . BK_OP_CLIP;
                        break;
                    case 'bk_content_wait_clip':
                        $wh_arr[] = " nns_status=" . BK_OP_WAIT_CLIP;
                        break;
                    case 'bk_content_doing':
                        $wh_arr[] = " nns_status=" . BK_OP_PROGRESS;
                        break;
                    case 'bk_content_cancel':
                        $wh_arr[] = " nns_status=" . BK_OP_CANCEL;
                        break;
                    case 'bk_unaudit':
                        $wh_arr[] = " nns_status=" . BK_OP_UNAUDIT;
                        break;
                    case 'bk_wait_sp':
                        $wh_arr[] = " nns_status=" . BK_OP_WAIT_SP;
                        break;
                    case 'bk_wait_sp_encode':
                        $wh_arr[] = " nns_status=" . BK_OP_WAIT_SP_ENCODE;
                        break;
                    case 'bk_wait_sp_encode_begin':
                        $wh_arr[] = " nns_status=" . BK_OP_WAIT_SP_ENCODE_BEGIN;
                        break;
                    case 'bk_fail_sp_encode':
                        $wh_arr[] = " nns_status=" . BK_OP_FAIL_SP_ENCODE;
                        break;
                }
            }
            if (isset($filter['nns_cp_id']) && strlen($filter['nns_cp_id']) > 0)
            {
                $wh_arr[] = " nns_cp_id='" . $filter['nns_cp_id'] . "'";
            }

            if (!empty($filter['state_queue']))
            {
                $state_queue = $filter['state_queue'];
                switch ($state_queue)
                {
                    case 'op_pause':
                        $wh_arr[] = " nns_state=1";
                        break;
                    case 'op_do':
                        $wh_arr[] = " nns_state=0";
                        break;
                }
            }

            if (!empty($wh_arr)) $sql .= " and " . implode(" and ", $wh_arr);
        }
        $count_sql = $sql;
        $count_sql = str_replace('*', ' count(*) as temp_count ', $count_sql);
        $sql .= " order by nns_weight desc,nns_create_time desc,nns_video_id asc,nns_op_mtime asc";
        $sql .= " limit $start,$size";
        $data = nl_db_get_all($sql, $db);
        $rows = nl_db_get_col($count_sql, $db);
        return array('data' => $data, 'rows' => $rows);
    }

    //获取这个列队的的列队最大个数
    public function get_cdn_execute_max($sp_id, $video_type)
    {
        set_time_limit(0);
        $sp_config = sp_model::get_sp_config($sp_id);
        if (isset($sp_config['cdn_' . $video_type . '_max']) && (int)$sp_config['cdn_' . $video_type . '_max'] > 0)
        {
            return array('ret' => true, 'max' => (int)$sp_config['cdn_' . $video_type . '_max']);
        } else
        {
            return array('ret' => true, 'max' => 100);
        }
    }



    /**
     * 这个方法后期禁用，没查询到前期任何方法来调用，后期又加了码率控制模式，使用了要出问题
     * liangpan  2016-03-23
     */
    //如果是混合模式
    public function q_add_task_mode($video_id, $video_type, $action, $sp_id = null)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        if ($video_type == BK_OP_MEDIA)
        {
            $sp_lists = sp_model::get_sp_list($sp_id);
            foreach ($sp_lists as $sp_list)
            {
                //查询sp——config
                $sp_config = json_decode($sp_list['nns_config'], true);
                if (isset($sp_config['cdn_import_media_mode']) && ((int)$sp_config['cdn_import_media_mode'] === 1 || (int)$sp_config['cdn_import_media_mode'] === 2))
                {
                    //获取任务名称
                    $task_arr = $this->get_task_name($video_id, $video_type);
                    $task_name = $task_arr['task_name'];
                    $params = array(
                        'ex_id' => $video_id,
                        'type' => $video_type,
                        'action' => $action,
                        'name' => $task_name,
                        'org_id' => $sp_list['nns_id']
                    );
                    $this->op_queue->add($db, $params);
                }
            }
        }
    }

    //添加存量任务

    public function add_task_default($sp_id, $name = null, $ids = null, $s_time = null, $e_time = null, $category = null, $limit = 0, $e_limit = 0)
    {

        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();


        //var_dump($sp_id);
        $where_arr = array();
        $where_arr[] = " nns_deleted!=1";


        $where_arr_tmp = array();
        if (!empty($name))
        {
            $where_arr[] = " (nns_name like '%$name%'  or nns_pinyin like '%$name%' or nns_id like '%$name%') ";
        }

        if (!empty($category) && $category != 10000)
        {
            $where_arr[] = " nns_category_id='$category' ";
        }

        if (!empty($s_time))
        {
            $s_time .= ' 00:00:00';
            $where_arr[] = " nns_create_time  >= '$s_time' ";
            $where_arr_tmp[] = " nns_create_time  >= '$s_time' ";
        }
        if (!empty($e_time))
        {
            $e_time .= ' 23:59:59';
            $where_arr[] = " nns_create_time  <= '$e_time' ";
            $where_arr_tmp[] = " nns_create_time  <= '$e_time' ";
        }

        if (!empty($ids))
        {
            $ids_arr = array_filter(explode(',', $ids));
            $where_arr[] = " nns_id in ('" . implode("','", $ids_arr) . "')";
        }

        $sql = "select count(1) as num from nns_vod where " . implode(" and ", $where_arr);


        if ($e_limit)
        {
            $num = 10;
        }

        //die($sql);
        $count = nl_query_by_db($sql, $db);
        $count = $count[0]['num'];

        if ($e_limit)
        {
            $count = $e_limit;
        }


        $num = 1;
        if ($e_limit)
        {
            if (intval($limit + $num) > $e_limit)
            {


                $num = intval($limit + $num) - $e_limit;

                //return array('count'=>$count,'data'=>'','limit'=>$limit,'is_end'=>1);
            }
        }

        // die($count);
        //echo $sql;
        $sql = "select * from nns_vod where " . implode(" and ", $where_arr) . " order by nns_modify_time desc   limit {$limit},$num";
        $infos = nl_query_by_db($sql, $db);

        //die($sql);
        if ($infos === true)
        {
            return array('count' => $count, 'data' => '', 'limit' => $limit, 'is_end' => 1);
        }
        // die($sql);
        // var_dump($infos);

        //if($limit>100){
        //	 return array('count'=>$count,'data'=>'','limit'=>$limit,'is_end'=>1);
        // }
        $arr_tmp = array();
        foreach ($infos as $key => $value)
        {
            $sql_video = "select nns_id from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='video' and nns_ref_id='{$value['nns_id']}'";
            $video_info = nl_db_get_one($sql_video, $db);
            //判断如果不存在才注入
            if (empty($video_info))
            {
                $this->q_add_task($value['nns_id'], BK_OP_VIDEO, BK_OP_ADD, $sp_id, null, true);
            }
            unset($sql_video, $video_info);
            $index_where = "";
            if (!empty($where_arr_tmp))
            {
                $index_where = implode(" and ", $where_arr_tmp);
            }
            $sql_index = "select * from nns_vod_index where nns_deleted!=1 and nns_vod_id='{$value['nns_id']}'  ";
            $list_index = nl_db_get_all($sql_index, $db);
            foreach ($list_index as $key => $value_index)
            {
                $sql_index_c2sql = "select nns_id from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='index' and nns_ref_id='{$value_index['nns_id']}'";
                $video_index_info = nl_db_get_one($sql_index_c2sql, $db);
                //判断如果不存在才注入
                if (empty($video_index_info))
                {
                    $this->q_add_task($value_index['nns_id'], BK_OP_INDEX, BK_OP_ADD, $sp_id, null, true);
                }
                unset($video_index_info, $sql_index_c2sql);
                $sql_media = "select * from nns_vod_media where nns_deleted!=1 and nns_vod_id='{$value['nns_id']}' and nns_vod_index_id='{$value_index['nns_id']}' ";
                $list_media = nl_db_get_all($sql_media, $db);
                foreach ($list_media as $key => $value_meida)
                {
                    $sql_media_c2sql = "select nns_id from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='media' and nns_ref_id='{$value_meida['nns_id']}'";
                    $video_media_info = nl_db_get_one($sql_media_c2sql, $db);
                    //判断如果不存在才注入
                    if (empty($video_media_info))
                    {
                        $this->q_add_task($value_meida['nns_id'], BK_OP_MEDIA, BK_OP_ADD, $sp_id, null, true);
                    }
                    unset($sql_media_c2sql, $video_media_info);
                }
            }
            $arr_tmp[] = array('nns_name' => $value['nns_name']);
        }

        if ($e_limit)
        {
            if (intval($limit + $num) > $e_limit)
            {
                //$num = intval($limit+30)-$e_limit;

                unset($db);

                return array('count' => $count, 'data' => $arr_tmp, 'limit' => $limit, 'is_end' => 1);
            }
        }

        $r = array('count' => $count, 'data' => $arr_tmp, 'limit' => intval($limit + count($infos)), 'is_end' => 0);
        unset($arr_tmp, $db);
        return $r;
    }

    //获取操作列队的日志
    public function get_task_queue_log($sp_id, $video_id, $video_type, $op_id, $star_num = 0, $limit = 12)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        //查询以及注入完成的
        $where = "";
        if ($video_type == BK_OP_VIDEO)
        {
            $where = " and  nns_video_id='$video_id'";
        } elseif ($video_type == BK_OP_INDEX)
        {
            $where = " and nns_index_id='$video_id'";
        } elseif ($video_type == BK_OP_MEDIA)
        {
            $where = " and nns_media_id='$video_id'";
        }
        $sql = "select * from nns_mgtvbk_op_log where nns_org_id='$sp_id' and nns_type='$video_type' $where and nns_op_id!='$op_id'";
        $count_sql = str_replace("*", "count(*)", $sql);
        $sql .= " order by nns_create_time desc limit $star_num,$limit";
        $count = nl_db_get_col($count_sql, $db);
        $data = nl_db_get_all($sql, $db);

        //查询正在注入的
        $sql_doing = "select * from nns_mgtvbk_op_log where nns_org_id='$sp_id' and nns_type='$video_type' $where and nns_op_id='$op_id' order by nns_create_time desc";

        $data_do = nl_db_get_all($sql_doing, $db);

        return array('num' => intval($count + count($data_do)), 'data' => $data, 'data_do' => $data_do);
    }

    public function q_re_clip($task_id)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();

        $sql = "select * from nns_mgtvbk_c2_task where nns_id='$task_id'";
        $info = nl_db_get_one($sql, $db);

        if (is_array($info) && $info != null)
        {
            $op_id = $info['nns_op_id'];
            nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_id='$task_id'", $db);
            $this->op_queue->re_clip($db, $op_id);
        }
        return true;
    }

    //暂停任务或则开启任务
    public function update_queue_state($ids, $bool)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $op_ids = explode(',', $ids);
        if ($bool)
        {
            $this->op_queue->resume($db, $op_ids);
        } else
        {
            $this->op_queue->pause($db, $op_ids);
        }
        return true;
    }

    public function delete_queue($ids)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $op_ids = explode(',', $ids);
        foreach ($op_ids as $id)
        {
            //echo "delete from nns_mgtvbk_op_queue where nns_id='$id'";
            $sql = "select * from nns_mgtvbk_op_queue where nns_id='{$ids}'";
            $task_info = nl_db_get_one($sql, $db);


            if ($task_info['nns_type'] == 'media')
            {
                $update_c2_task = "update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_org_id='{$task_info['nns_org_id']}' and nns_type='media' and nns_ref_id='{$task_info['nns_media_id']}'";
            } elseif ($task_info['nns_type'] == 'index')
            {
                $update_c2_task = "update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_org_id='{$task_info['nns_org_id']}' and nns_type='index' and nns_ref_id='{$task_info['nns_index_id']}'";
            } elseif ($task_info['nns_type'] == 'video')
            {
                $update_c2_task = "update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_org_id='{$task_info['nns_org_id']}' and nns_type='video' and nns_ref_id='{$task_info['nns_video_id']}'";
            }
            nl_execute_by_db($update_c2_task, $db);

            nl_execute_by_db("delete from nns_mgtvbk_op_queue where nns_id='$id'", $db);
        }
        return true;
    }

    //全部暂停或则全部取消暂停
    public function update_queue_all_state($ids, $type, $bool)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        //$op_ids =  explode(',',$ids);
        $sql = "select * from nns_mgtvbk_op_queue where nns_id='{$ids}'";
        $info = nl_db_get_one($sql, $db);
        $state = 0;
        if ($bool)
        {
            $state = 0;
        } else
        {
            $state = 1;
        }
        if (is_array($info))
        {

            if ($type == 'video')
            {
                $update_sql = "update nns_mgtvbk_op_queue set nns_state=$state where nns_org_id='{$info['nns_org_id']}' and nns_video_id='{$info['nns_video_id']}'";
            } elseif ($type == 'index')
            {
                $update_sql = "update nns_mgtvbk_op_queue set nns_state=$state where nns_org_id='{$info['nns_org_id']}' and nns_video_id='{$info['nns_video_id']}' and nns_index_id='{$info['nns_index_id']}'";
            }
            //die($update_sql);
            nl_execute_by_db($update_sql, $db);
            return true;
        }
        return false;

    }

    //先删除在注入一条数据库
    public function q_add_media_task($media_id, $sp_id = null)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $sql = "select * from nns_vod_media where nns_id='$media_id'";
        $media_info = nl_db_get_one($sql, $db);
        nl_execute_by_db("update nns_vod_media set nns_status=3,nns_action='destroy',nns_deleted=1,nns_modify_time=now() where nns_id='$media_id'", $db);
        $new_id = np_guid_rand();
        $media_info['nns_id'] = $new_id;
        $media_info['nns_status'] = 1;
        $media_info['nns_action'] = 'add';
        $media_info['nns_create_time'] = date('Y-m-d H:i:s');
        unset($media_info['nns_modify_time']);
        unset($media_info['nns_integer_id']);
        $params = array(
            'ex_id' => $media_id,
            'type' => 'media',
            'action' => BK_OP_DELETE,
            //'name'=>$task_name,
        );

        $params_new = array(
            'ex_id' => $new_id,
            'type' => 'media',
            'action' => BK_OP_ADD,
            //'name'=>$task_name,
        );
        $re = nl_db_insert($db, 'nns_vod_media', $media_info);

        $this->q_add_task_op_mgtv($media_id, 'media', BK_OP_DELETE);
        $this->q_add_task_op_mgtv($new_id, 'media', BK_OP_ADD);
        return true;

        $sp_list = sp_model::get_sp_list($sp_id);
        foreach ($sp_list as $sp)
        {
            $sp_config = json_decode($sp['nns_config'], true);
            if (isset($sp_config['cdn_import_media_mode']) && ((int)$sp_config['cdn_import_media_mode'] === 1 || (int)$sp_config['cdn_import_media_mode'] === 2))
            {
                //如果是混合模式注入么率最高的
                $sql = "select * from nns_vod_media where nns_vod_id='{$media_info['nns_vod_id']}' and nns_vod_index_id='{$media_info['nns_vod_index_id']}' and nns_deleted!=1 order by nns_kbps desc limit 1";
                $media_info_new = nl_db_get_one($sql, $db);
                $media_id_new = $media_info_new['nns_id'];
                //获取任务名称
                $task_arr = $this->get_task_name($media_id, BK_OP_MEDIA);
                $task_name = $task_arr['task_name'];
                $asset_id = $task_arr['asset_id'];
                $params_new['name'] = $task_name;
                $params_new['ex_id'] = $media_id_new;
            } else
            {
                //获取任务名称
                $task_arr = $this->get_task_name($media_id, BK_OP_MEDIA);
                $task_name = $task_arr['task_name'];
                $asset_id = $task_arr['asset_id'];
                $params['name'] = $task_name;
                $params_new['name'] = $task_name;
            }
            $params['org_id'] = $sp['nns_id'];
            $this->op_queue->add($db, $params);
            $params_new['org_id'] = $sp['nns_id'];
            $this->op_queue->add($db, $params_new);
        }
        return true;
    }

    //检查这个任务是否被删除了
    public function check_task_status($op_id)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $sql = "select * from nns_mgtvbk_op_queue where nns_id='$op_id'";
        $task_info = nl_db_get_one($sql, $db);

        if (is_array($task_info))
        {
            if ($task_info['nns_status'] == 1)
            {
                if($task_info['nns_type'] == 'epg_file')
                {//这里后期点播直播c2队列分开后，可以用switch进行条件选择。
                    $sql_c2task = "select * from nns_mgtvbk_file_task where nns_op_id='$op_id' and nns_org_id='{$task_info['nns_org_id']}'";
                }
                else
                {
                    $sql_c2task = "select * from nns_mgtvbk_c2_task where nns_op_id='$op_id' and nns_org_id='{$task_info['nns_org_id']}'";
                }
                $sp_task_info = nl_db_get_one($sql_c2task, $db);
                if (is_array($sp_task_info))
                {
                    if ($sp_task_info['nns_status'] == 7 || $sp_task_info['nns_status'] == 100)
                    {
                        if ($sp_task_info['nns_type'] == 'epg_file')
                        {
                            nl_execute_by_db("update nns_mgtvbk_file_task set nns_status=1,nns_status=97 where nns_id='{$sp_task_info['nns_id']}'", $db);
                        }
                        else
                        {
                            nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=1,nns_status=97 where nns_id='{$sp_task_info['nns_id']}'", $db);
                        }
                    }

                    include_once 'sp_model.php';
                    $sp_config = sp_model::get_sp_config($sp_task_info['nns_org_id'], $sp_task_info['nns_type'] . '_' . $sp_task_info['nns_action']);
                    $q_report_task = $this->is_succ_state($sp_config, $sp_task_info);

                    if ($q_report_task === true)
                    {
                        //获取这个sp的后置sp
                        $sp_config = sp_model::get_sp_config($sp_task_info['nns_org_id']);

                        if (isset($sp_config['after_execute_sp']) && !empty($sp_config['after_execute_sp']))
                        {
                            //获取前置sp的列队信息
                            //print_r($c2_task_info);die;
                            if ($sp_task_info['nns_op_id'])
                            {
                                $op_before_detail = $this->get_q_task_detail($sp_task_info['nns_op_id']);
                                //获取后置sp的相同单位的队列id
                                $params = array(
                                    'video_id' => $op_before_detail['q_task_info']['nns_video_id'],
                                    'index_id' => $op_before_detail['q_task_info']['nns_index_id'],
                                    'media_id' => $op_before_detail['q_task_info']['nns_media_id'],
                                    'org_id' => $sp_config['after_execute_sp'],
                                    'type' => $op_before_detail['q_task_info']['nns_type'],
                                    'action' => $op_before_detail['q_task_info']['nns_action'],
                                );

                                $op_after = $this->__q_get_after_op($op_before_detail, $params);

                                if ((int)$op_after['state'] === 100)
                                {
                                    $op_after_id = $op_after['data'];//获取后置opid
                                    $ex_url = '';
                                    if ($sp_task_info['nns_type'] == 'media' && $sp_task_info['nns_type'] != 'destroy')
                                    {
                                        $c2_task_info_exdata = $sp_task_info['nns_ex_url'];
                                        $ex_url = json_encode(array(
                                            'url' => $c2_task_info_exdata,
                                            'path' => $c2_task_info_exdata,
                                            'size' => $sp_task_info['nns_file_size'],
                                            'clip_id' => $sp_task_info['nns_clip_task_id'],
                                            'clip_date' => $sp_task_info['nns_clip_date'],
                                            'file_md5' => $sp_task_info['nns_file_md5'],
                                            'policy' => $sp_task_info['nns_cdn_policy'],
                                        ));
                                    }
                                    $rs = $this->op_queue->wait_op_execute($db, $op_after_id, $ex_url);
                                    if ((int)$rs['state'] == 100)
                                    {
                                        //如果获取到后置的任务才将前置设置为ok
                                        $r = $this->op_queue->task_ok($db, $op_id, $sp_task_info, false);
                                    }
                                }
                            }
                        } else
                        {
                            $this->op_queue->task_ok($db, $op_id, $sp_task_info, false);
                        }
                    }
                }
                else
                {
                    nl_execute_by_db("update nns_mgtvbk_op_queue set nns_status=0  where nns_id='$op_id'", $db);
                }
            }
            if ($task_info['nns_action'] != 'destroy')
            {
                if ($task_info['nns_type'] == 'video')
                {
                    $sql_info = "select * from nns_vod where nns_id='{$task_info['nns_video_id']}'";
                }
                elseif ($task_info['nns_type'] == 'index')
                {
                    $sql_info = "select * from nns_vod_index where nns_id='{$task_info['nns_index_id']}'";
                }
                elseif ($task_info['nns_type'] == 'media')
                {
                    $sql_info = "select * from nns_vod_media where nns_id='{$task_info['nns_media_id']}'";
                }
                elseif ($task_info['nns_type'] == 'live')
                {
                    $sql_info = "select * from nns_live where nns_id='{$task_info['nns_video_id']}'";
                }
                elseif ($task_info['nns_type'] == 'live_media')
                {
                    $sql_info = "select * from nns_live_media where nns_id='{$task_info['nns_media_id']}'";
                }
                elseif ($task_info['nns_type'] == 'playbill')
                {
                    $sql_info = "select * from nns_live_playbill_item where nns_id='{$task_info['nns_media_id']}'";
                }
//                elseif ($task_info['nns_type'] == 'media')
//                {
//                    $sql_info = "select * from nns_live_playbill_item where nns_id='{$task_info['nns_media_id']}'";
//                }
                elseif ($task_info['nns_type'] == 'file')
                {
                    $sql_info = "select * from nns_file_package where nns_id='{$task_info['nns_video_id']}'";
                }
                elseif ($task_info['nns_type'] == 'epg_file')
                {
                    $sql_info = "select * from nns_epg_file where nns_id='{$task_info['nns_index_id']}'";
                }
                $info = nl_db_get_one($sql_info, $db);
                if (empty($info))
                {
                    return array('nns_id' => $op_id, 'text' => '资源库数据已删除', 'check' => 1);
                }
                else
                {
                    if ($info['nns_deleted'] == '1')//已删除的内容
                    {
                        return array('nns_id' => $op_id, 'text' => '资源库数据已删除', 'check' => 1);
                    }
                    //print_r($task_info);
                    //if($task_info['nns_type']=='media'&&($task_info['nns_status']!=0||$task_info['nns_status']!=1||$task_info['nns_status']!=2)){
                    //当前类型片源，且正在切片中
                    if ($task_info['nns_type'] == 'media' && $task_info['nns_status'] == 3)
                    {
                        //查询op_id  是否是切片失败

                        $sql = "select * from nns_mgtvbk_clip_task where nns_org_id='{$task_info['nns_org_id']}' and nns_op_id='$op_id' and nns_state!='cancel' order by nns_create_time desc limit 1";
                        //echo $sql;
                        $info = nl_db_get_one($sql, $db);
                        if (empty($info)) //没有查询到正在切片状态的中的片源
                        {
                            return array('nns_id' => $op_id, 'text' => '可以删除', 'check' => 1);
                        }
                        else
                        {
                            if ($info['nns_state'] == 'get_media_url_fail')
                            {
                                return array('nns_id' => $op_id, 'text' => '获取下载地址失败', 'check' => 2);
                            }
                            elseif ($info['nns_state'] == 'download_fail')
                            {
                                //下载失败反馈 feijian.gao start-->
                                $sp_config = sp_model::get_sp_config($task_info['nns_org_id']);
                                if ($sp_config["cdn_message_feedback_model"] == 'http')
                                {
                                    $this->unicom_d3_return_download_fail($task_info);
                                }
                                //end-->
                                return array('nns_id' => $op_id, 'text' => '下载失败', 'check' => 3);
                            }
                            elseif ($info['nns_state'] == 'clip_fail')
                            {
                                return array('nns_id' => $op_id, 'text' => '切片失败', 'check' => 4);
                            }
                            elseif ($info['nns_state'] == 'cancel')
                            {
                                return array('nns_id' => $op_id, 'text' => '可以删除', 'check' => 1);
                            }
                            elseif ($info['nns_state'] == 'fail')
                            {
                                return array('nns_id' => $op_id, 'text' => '可以删除', 'check' => 1);
                            }
                            else
                            {
                                return array('nns_id' => $op_id, 'text' => '队列处理中', 'check' => 0);
                            }
                        }
                    }
                    elseif ($task_info['nns_status'] == 1)
                    {
//                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='{$task_info['nns_org_id']}' and nns_op_id='$op_id'";
//                        $info = nl_db_get_one($sql, $db);
//                        if (empty($info))
//                        {
//                            return array('nns_id' => $op_id, 'text' => '可以删除', 'check' => 1);
//                        }
//                        else
//                        {
                            if ($sp_task_info['nns_status'] == -1)
                            {
                                return array('nns_id' => $op_id, 'text' => '注入失败', 'check' => 6);
                            }
                            elseif ($sp_task_info['nns_status'] == 5)
                            {
                                return array('nns_id' => $op_id, 'text' => '正在注入CDN', 'check' => 0);
                            }
                            elseif ($sp_task_info['nns_status'] == 0)
                            {
                                return array('nns_id' => $op_id, 'text' => 'CDN注入成功', 'check' => 0);
                            }
                            elseif ($sp_task_info['nns_status'] == 7)
                            {
                                return array('nns_id' => $op_id, 'text' => '注入取消', 'check' => 7);
                            }
                            elseif ($sp_task_info['nns_status'] == 6)
                            {
                                return array('nns_id' => $op_id, 'text' => '等待获取播放串', 'check' => 0);
                            }
                            elseif ($sp_task_info['nns_status'] == 8)
                            {
                                return array('nns_id' => $op_id, 'text' => '正在获取播放串', 'check' => 0);
                            }
                            elseif ($sp_task_info['nns_status'] == 9)
                            {
                                return array('nns_id' => $op_id, 'text' => '获取播放串失败', 'check' => 9);
                            }
//                        }
                    }

                    if ($info['nns_deleted'] != 1)
                    {
                        return array('nns_id' => $op_id, 'text' => '数据正常', 'check' => 0);
                    }
                    else
                    {
                        if ($info['nns_state'] != 1 && $task_info['nns_type'] == 'playbill')
                        {
                            return array('nns_id' => $op_id, 'text' => '数据正常', 'check' => 0);
                        }
                        return array('nns_id' => $op_id, 'text' => '资源库数据已删除', 'check' => 1);
                    }
                }
            }
            else
            {
                return array('nns_id' => $op_id, 'text' => '数据正常', 'check' => 0);
            }
        }
        else
        {
            return array('nns_id' => $op_id, 'text' => '数据异常', 'check' => 1);
        }

    }


    //修改成默认的执行状态
    public function update_queue_default_state($op_id)
    {
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $sql = "select * from nns_mgtvbk_op_queue where nns_id='$op_id'";
        $task_info = nl_db_get_one($sql, $db);
        //如果是等待前置sp，就不执行
        if ($task_info['nns_status'] == 7)
        {
            return false;
        }

        if ($task_info['nns_type'] == 'media')
        {
            if ($task_info['nns_action'] != 'destroy')
            {
                //-->start xingcheng.hu 添加不切片sp队列状态修改
                $sql_sp = "select * from nns_mgtvbk_sp where nns_id='" . $task_info['nns_org_id'] . "'";
                $sp = nl_db_get_one($sql_sp, $db);
                $sp_config = json_decode($sp['nns_config'], true);
                if (isset($sp_config['disabled_clip']) && $sp_config['disabled_clip'] == 0)
                {
                    //<--end
                    $update_sql = "update nns_mgtvbk_op_queue set nns_status=2 where nns_id='$op_id'";
                } else
                {
                    $update_sql = "update nns_mgtvbk_op_queue set nns_status=0 where nns_id='$op_id'";
                }
            } else
            {
                $update_sql = "update nns_mgtvbk_op_queue set nns_status=0 where nns_id='$op_id'";
            }
            nl_execute_by_db("update nns_mgtvbk_clip_task set nns_state='cancel' where nns_op_id='$op_id'", $db);
        } else
        {
            $update_sql = "update nns_mgtvbk_op_queue set nns_status=0 where nns_id='$op_id'";
        }

        if ($task_info['nns_type'] == 'media')
        {
            $update_c2_task = "update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_org_id='{$task_info['nns_org_id']}' and nns_type='media' and nns_ref_id='{$task_info['nns_media_id']}'";
        } elseif ($task_info['nns_type'] == 'index')
        {
            $update_c2_task = "update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_org_id='{$task_info['nns_org_id']}' and nns_type='index' and nns_ref_id='{$task_info['nns_index_id']}'";
        } elseif ($task_info['nns_type'] == 'video')
        {
            $update_c2_task = "update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_org_id='{$task_info['nns_org_id']}' and nns_type='video' and nns_ref_id='{$task_info['nns_video_id']}'";
        }
        nl_execute_by_db($update_c2_task, $db);
        return nl_execute_by_db($update_sql, $db);
    }

    public function update_queue_default_state_all($op_id)
    {
        $op_id_arr = explode(',', $op_id);
        foreach ($op_id_arr as $id)
        {
            if ($id)
            {
                $this->update_queue_default_state($id);
            }
        }
        return true;
    }

    public function c2_task_start_all($op_id,$sp_id)
    {
        $dc = nl_get_dc(array(
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $db = $dc->db();
        $sql = "select * from nns_mgtvbk_sp where nns_id='" . $sp_id . "'";
        $sp_conf = nl_db_get_one($sql, $db);
        $sp_conf = json_decode($sp_conf['nns_config'], true);
        i_write_log_core(var_export($sp_conf, true), 'get_task_config/' . $sp_id);
        //中心同步指令暂停下发【0:开启；1:关闭】
        if (isset($sp_conf['close_queue']) && (int)$sp_conf['close_queue'] === 1)
        {
            //unset($db);
            return false;
        }
        $op_id_arr = explode(',', $op_id);
        foreach ($op_id_arr as $id)
        {
            if ($id)
            {
                $op_result=nl_op_queue::query_op_queue_info_by_id($dc,$id);
                if($op_result['ret']==0 && is_array($op_result['data_info']) && $op_result['data_info'][0]['nns_status']=='0')
                {
                    $this->c2_task_start($id,$sp_id);
                }
            }
        }
        return true;
    }

    //手动注入c2_task
    public function c2_task_start($op_id,$sp_id)
    {
        $dc = nl_get_dc(array(
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $db = $dc->db();
        $sql = "select * from nns_mgtvbk_sp where nns_id='" . $sp_id . "'";
        $sp_conf = nl_db_get_one($sql, $db);
        $sp_conf = json_decode($sp_conf['nns_config'], true);

        $sql = "select * from nns_mgtvbk_op_queue where nns_id='" . $op_id . "'";
        $tasks = nl_db_get_all($sql, $db);

        if(!empty($tasks) && count($tasks)>0){

            //查询当前正在执行的有多少记录
            /*$str="";
            if($sp_id=='yntt'||$sp_id=='ynyd'||$sp_id=='dxjd' || $sp_id=='sdlt'){
                $str = "and nns_epg_status=97";
            }elseif($sp_id=='sihua'){
                $str = "and nns_status in (1,5) and nns_epg_status=97";
            }elseif($sp_id=='shanghai_mobile'){
                $str = "and nns_status in (1,5,6,8)";
            }else{
                $str = "and nns_epg_status=97 and nns_status in (0,1,5)  ";
            }
            $sql_video_cont = "select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='video'   $str";
            */

            //$num_video = nl_db_get_col($sql_video_cont, $db);
            //当前正在执行的任务数(类型为主媒资)
            $num_video = 1;
            //获取CDN注入主媒资队列上限
            $num_video_set = strlen($sp_conf['cdn_video_max']) > 0 ? (int)$sp_conf['cdn_video_max'] : 100;

            //$sql_index_cont = "select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='index'   $str";
            //$num_index = nl_db_get_col($sql_index_cont, $db);
            //当前正在执行的任务数(类型为分集)
            $num_index = 1;
            //获取CDN注入分集队列上限
            $num_index_set = strlen($sp_conf['cdn_index_max']) > 0 ? (int)$sp_conf['cdn_index_max'] : 100;

            //$sql_media_cont = "select count(*) as num from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='media'   $str";
            //$num_media = nl_db_get_col($sql_media_cont, $db);
            //当前正在执行的任务数(类型为片源)
            $num_media = 1;
            //获取CDN注入片源队列上限
            $num_media_set = strlen($sp_conf['cdn_media_max']) > 0 ? (int)$sp_conf['cdn_media_max'] : 100;
            //遍历从nns_mgtvbk_op_queue中取出的任务
            $temp_num = 0;

            if (isset($sp_conf['create_media_mode']) && $sp_conf['create_media_mode'] == '1' && isset($sp_conf['media_service_type']) && strlen($sp_conf['media_service_type']) > 0)
            {
                include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/vod_media/vod_media.class.php';
                include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/op_queue/op_queue.class.php';
            }
            foreach ($tasks as $task_info)
            {

                $task_info['nns_ex_data'] = json_decode($task_info['nns_ex_data'], true);

                $int_nns_is_group = isset($task_info['nns_is_group']) ? $task_info['nns_is_group'] : 0;
                $int_nns_weight = isset($task_info['nns_weight']) ? $task_info['nns_weight'] : 0;
                $str_c2_nns_cp_id = isset($task_info['nns_cp_id']) ? $task_info['nns_cp_id'] : '';

                np_runtime_ex('task' . $task_info['nns_id'], false);
                $temp_num++;
                //echo "<hr/>";
                //echo "第[{$temp_num}]次循环<br/>";
                //当前正在执行的任务数
                //echo $num_video . "----video<br/>";
                //echo $num_index . "----index<br/>";
                //echo $num_media . "----media<br/>";
                if ($task_info['nns_type'] == 'video')
                {
                    //获取op_queue任务名称
                    $task_arr = $this->get_task_name($task_info['nns_video_id'], $task_info['nns_type']);
                    //如果当前正在执行的c2任务数(主媒资)>=CDN注入主媒资队列上限
                    if ($num_video >= $num_video_set)
                    {
                       // echo '1--video';
                        //echo "<br/>";
// 							break;
                        continue;
                    }
                } elseif ($task_info['nns_type'] == 'index')
                {
                    //获取op_queue任务名称
                    $task_arr = $this->get_task_name($task_info['nns_index_id'], $task_info['nns_type']);
                    //如果当前正在执行的c2任务数(分集)>=CDN注入分集队列上限
                    if ($num_index >= $num_index_set)
                    {
                        //echo '1--index';
                        //echo "<br/>";
// 							break;
                        continue;
                    }
                } elseif ($task_info['nns_type'] == 'media')
                {
                    //获取op_queue任务名称
                    $task_arr = $this->get_task_name($task_info['nns_media_id'], $task_info['nns_type']);

                    if (isset($task_arr['nns_media_encode_flag']) && $task_arr['nns_media_encode_flag'] != 0 && strlen($task_arr['cp_id']) > 0)
                    {
                        if (!isset($temp_result_cp_info[$task_arr['cp_id']]))
                        {
                            $result_cp_info = nl_cp::query_by_id_by_db($db, $task_arr['cp_id']);
                            $result_cp_info = (isset($result_cp_info['data_info']['nns_config']) && strlen($result_cp_info['data_info']['nns_config']) > 0) ? json_decode($result_cp_info['data_info']['nns_config'], true) : null;
                            $temp_result_cp_info[$task_arr['cp_id']] = $result_cp_info;
                        } else
                        {
                            $result_cp_info = $temp_result_cp_info[$task_arr['cp_id']];
                        }
                    }
                    if (isset($sp_conf['create_media_mode']) && $sp_conf['create_media_mode'] == '1' && isset($sp_conf['media_service_type'])
                        && strlen($sp_conf['media_service_type']) > 0 && (isset($task_arr['nns_media_encode_flag']) && in_array($task_arr['nns_media_encode_flag'], array('0', '1'))))
                    {
                        $result_temp_media = nl_vod_media_v2::query_by_id($dc, $task_info['nns_media_id']);
                        if ($result_temp_media['ret'] != 0 || !isset($result_temp_media['data_info']) || !is_array($result_temp_media['data_info']) || empty($result_temp_media['data_info']))
                        {
                            //echo "<font color='red'>查询片源数据库执行失败:</font><br>";
                            //var_dump($result_temp_media);
                            continue;
                        }
                        $result_temp_media = $result_temp_media['data_info'];
                        unset($result_temp_media['nns_integer_id']);
                        $temp_message_id = '';
                        if (isset($sp_conf['fuse_platform_mark']) && strlen($sp_conf['fuse_platform_mark']) > 0)
                        {
                            $result_media_org_media = nl_vod_media_v2::query_media_org_exsist($dc, $result_temp_media['nns_import_id'], substr($result_temp_media['nns_cp_id'], 5), $result_temp_media['nns_import_source']);
                            if ($result_media_org_media['ret'] != 0)
                            {
                                //echo "<font color='red'>配置了融合平台数据但是数据库查询失败:</font><br>";
                                //var_dump($result_media_org_media);
                                continue;
                            }
                            if (!isset($result_media_org_media['data_info']) || !is_array($result_media_org_media['data_info']) || empty($result_media_org_media['data_info']))
                            {
                                //echo "<font color='red'>配置了融合平台数据,查询数据成功，但是没数据:</font><br>";
                                //var_dump($result_media_org_media, $task_info['nns_id']);
                                nl_op_queue::edit($dc, array('nns_state' => 1), $task_info['nns_id']);
                                continue;
                            }
                            $result_c2_task_data = nl_c2_task::query_c2_exsist($dc, 'media', $result_media_org_media['data_info']['nns_id'], $sp_conf['fuse_platform_mark']);
                            if ($result_c2_task_data['ret'] != 0)
                            {
                                //echo "<font color='red'>配置了融合平台数据,查询C2数据库执行失败:</font><br>";
                                //var_dump($result_c2_task_data);
                                continue;
                            }
                            if (!isset($result_c2_task_data['data_info'][0]) || !is_array($result_c2_task_data['data_info'][0]) || empty($result_c2_task_data['data_info'][0]))
                            {
                                //echo "<font color='red'>配置了融合平台数据,查询C2数据库,查询数据成功，但是没数据:</font><br>";
                                //var_dump($result_c2_task_data);
                                continue;
                            } else
                            {
                                $temp_message_id = (isset($result_c2_task_data['data_info'][0]['nns_message_id']) && strlen($result_c2_task_data['data_info'][0]['nns_message_id']) > 0) ? $result_c2_task_data['data_info'][0]['nns_message_id'] : '';
                            }
                        }
                        $result_temp_media['nns_id'] = np_guid_rand();
                        $result_temp_media['nns_encode_flag'] = '2';
                        $result_temp_media['nns_import_id'] = $result_temp_media['nns_import_id'] . '_' . $sp_id;
                        $result_temp_media['nns_media_service'] = $sp_conf['media_service_type'];
                        $result_media_exsist = nl_vod_media_v2::query_media_exsist($dc, $result_temp_media['nns_import_id'], $result_temp_media['nns_cp_id'], $result_temp_media['nns_import_source'], $sp_conf['media_service_type']);
                        if ($result_media_exsist['ret'] != 0)
                        {
                            //echo "<font color='red'>查询片源是否存在数据库失败:</font><br>";
                            //var_dump($result_media_exsist);
                            continue;
                        }
                        if (!isset($result_media_exsist['data_info']) || !is_array($result_media_exsist['data_info']) || empty($result_media_exsist['data_info']))
                        {
                            $result_vod_media_add = nl_vod_media_v2::add($dc, $result_temp_media);
                            if ($result_vod_media_add['ret'] != 0)
                            {
                                //echo "<font color='red'>片源添加失败:</font><br>";
                                //var_dump($result_vod_media_add);
                                continue;
                            }
                        } else
                        {
                            $result_temp_media['nns_id'] = $result_media_exsist['data_info']['nns_id'];
                            $result_vod_media_edit = nl_vod_media_v2::edit($dc, array('nns_media_service' => $result_temp_media['nns_media_service']), $result_temp_media['nns_id']);
                            if ($result_vod_media_edit['ret'] != 0)
                            {
                                //echo "<font color='red'>片源修改失败:</font><br>";
                                //var_dump($result_vod_media_edit);
                                continue;
                            }
                        }
                        $temp_op_queue_data = $task_info;
                        $temp_op_queue_data['nns_ex_data'] = is_array($temp_op_queue_data['nns_ex_data']) ? json_encode($temp_op_queue_data['nns_ex_data']) : '';
                        $temp_op_queue_data['nns_media_id'] = $result_temp_media['nns_id'];
                        $temp_op_queue_data['nns_name'] = $temp_op_queue_data['nns_name'] . " [{$sp_conf['media_service_type']}]";
                        $temp_op_queue_data['nns_id'] = np_guid_rand();
                        if (strlen($temp_message_id) > 0)
                        {
                            $temp_op_queue_data['nns_message_id'] = $temp_message_id;
                        }
                        $result_op_queue_add = nl_op_queue::add($dc, $temp_op_queue_data);
                        if ($result_op_queue_add['ret'] != 0)
                        {
                            //echo "<font color='red'>OP queue 队列添加失败:</font><br>";
                            //var_dump($result_op_queue_add);
                            continue;
                        }
                        $result_op_queue_del = nl_op_queue::delete_op_queue($dc, array($task_info['nns_id']));
                        if ($result_op_queue_del['ret'] != 0)
                        {
                            //echo "<font color='red'>OP queue 队列删除失败:</font><br>";
                            //var_dump($result_op_queue_del);
                            continue;
                        }
                        continue;
                    }
                    //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                    if ($num_media >= $num_media_set)
                    {
                        //echo '1--media';
                        //echo "<br/>";
// 							break;
                        continue;
                    }
                } elseif ($task_info['nns_type'] == 'live_media')
                {
                    //获取op_queue任务名称
                    $task_arr = $this->get_task_name($task_info['nns_media_id'], $task_info['nns_type']);
                    //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
// 					    if($num_media>=$num_media_set){
// 					        echo '1--media';echo "<br/>";
                    // 							break;
// 					        continue;
// 					    }
                } elseif ($task_info['nns_type'] == 'live')
                {
                    //获取op_queue任务名称
                    $task_arr = $this->get_task_name($task_info['nns_video_id'], $task_info['nns_type']);
                    //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                    // 					    if($num_media>=$num_media_set){
                    // 					        echo '1--media';echo "<br/>";
                    // 							break;
                    // 					        continue;
                    // 					    }
                } elseif ($task_info['nns_type'] == 'playbill')
                {
                    //获取op_queue任务名称
                    $task_arr = $this->get_task_name($task_info['nns_media_id'], $task_info['nns_type']);
                    //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                    // 					    if($num_media>=$num_media_set){
                    // 					        echo '1--media';echo "<br/>";
                    // 							break;
                    // 					        continue;
                    // 					    }
                } elseif ($task_info['nns_type'] == 'file')
                {
                    //获取op_queue任务名称
                    $task_arr = $this->get_task_name($task_info['nns_video_id'], $task_info['nns_type']);
                    //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                    // 					    if($num_media>=$num_media_set){
                    // 					        echo '1--media';echo "<br/>";
                    // 							break;
                    // 					        continue;
                    // 					    }
                } elseif ($task_info['nns_type'] == 'product')
                {
                    //获取op_queue任务名称
                    $task_arr = $this->get_task_name($task_info['nns_video_id'], $task_info['nns_type']);
                    //如果当前正在执行的c2任务数(片源)>=CDN注入片源队列上限
                    // 					    if($num_media>=$num_media_set){
                    // 					        echo '1--media';echo "<br/>";
                    // 							break;
                    // 					        continue;
                    // 					    }
                }
                $task_info['nns_name'] = ($task_info['nns_type'] == 'media' && isset($task_arr['nns_media_encode_flag']) && $task_arr['nns_media_encode_flag'] != 0) ? $task_info['nns_name'] : $task_arr['task_name'];
                //如果是主媒资并且不是删除操作，则将数据写入nns_mgtvbk_category_content表中
                if ($task_info['nns_type'] == BK_OP_VIDEO && $task_info['nns_action'] != BK_OP_DELETE)
                {
                    //主媒资信息
                    $vod_info = video_model::get_vod_info($task_info['nns_video_id']);
                    $asset_categori_id = $vod_info['nns_category_id'];//资源库栏目ID
                    $sp_category = sp_category_model::get_bind_sp_category($sp_id, $asset_categori_id);
                    if (is_array($sp_category))
                    {
                        foreach ($sp_category as $category)
                        {
                            $data = array(
                                'nns_id' => np_guid_rand($sp_id),
                                'nns_org_id' => $sp_id,
                                'nns_category_id' => $category['nns_id'],
                                'nns_category_name' => $category['nns_name'],
                                'nns_video_id' => $task_info['nns_video_id'],
                                'nns_video_name' => $vod_info['nns_name'],
                                'nns_create_time' => date('Y-m-d H:i:s'),
                                'nns_pinyin' => $vod_info['nns_pinyin'],
                                'nns_video_type' => 0,
                                'nns_status' => 0,
                            );
                            @nl_db_insert($db, 'nns_mgtvbk_category_content', $data);
                        }
                    }
                }
                $nns_ref_id = "";
                $nns_parent_id = "";

                //查询任务信息
                switch ($task_info['nns_type'])
                {
                    case BK_OP_VIDEO:
                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_video_id']}'";
                        //nns_ref_id为nns_vod表的guid;
                        $nns_ref_id = $task_info['nns_video_id'];
                        $nns_parent_id = 0;
                        break;
                    case BK_OP_INDEX:
                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_index_id']}'";
                        //nns_ref_id为nns_vod_index表的guid;
                        $nns_ref_id = $task_info['nns_index_id'];
                        //nns_src_id为nns_vod表的guid
                        $nns_parent_id = $task_info['nns_video_id'];
                        break;
                    case BK_OP_MEDIA:
                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_media_id']}'";
                        //nns_ref_id为nns_vod_media表的guid;
                        $nns_ref_id = $task_info['nns_media_id'];
                        //nns_src_id为nns_vod_index表的guid
                        $nns_parent_id = $task_info['nns_index_id'];
                        break;
                    case BK_OP_LIVE:
                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_video_id']}'";
                        //nns_ref_id为nns_vod_media表的guid;
                        $nns_ref_id = $task_info['nns_video_id'];
                        //nns_src_id为nns_vod_index表的guid
                        $nns_parent_id = 0;
                        break;
                    case BK_OP_LIVE_MEDIA:
                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_media_id']}'";
                        //nns_ref_id为nns_vod_media表的guid;
                        $nns_ref_id = $task_info['nns_media_id'];
                        //nns_src_id为nns_vod_index表的guid
                        $nns_parent_id = $task_info['nns_index_id'];
                        break;
                    case BK_OP_PLAYBILL:
                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_media_id']}'";
                        //nns_ref_id为nns_vod_media表的guid;
                        $nns_ref_id = $task_info['nns_media_id'];
                        //nns_src_id为nns_vod_index表的guid
                        $nns_parent_id = $task_info['nns_index_id'];
                        break;
                    case BK_OP_FILE:
                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_video_id']}'";
                        //nns_ref_id为nns_vod_media表的guid;
                        $nns_ref_id = $task_info['nns_video_id'];
                        //nns_src_id为nns_vod_index表的guid
                        $nns_parent_id = 0;
                        break;
                    case BK_OP_PRODUCT:
                        $sql = "select * from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='{$task_info['nns_type']}' and nns_ref_id='{$task_info['nns_video_id']}'";
                        //nns_ref_id为nns_vod_media表的guid;
                        $nns_ref_id = $task_info['nns_video_id'];
                        //nns_src_id为nns_vod_index表的guid
                        $nns_parent_id = 0;
                        break;
                }
                //查询当前任务是否在C2任务表中
                $c2_task_info = nl_db_get_one($sql, $db);
// 					if($sp_id == 'starcor_cdn' && is_array($c2_task_info) && !empty($c2_task_info))
// 					{
// 					    nl_execute_by_db("delete from nns_mgtvbk_op_queue where nns_id='{$task_info['nns_id']}' and nns_org_id='{$sp_id}' ", $db);
// 					    continue;
// 					}
                //查询C2表中当前操作是否为最终状态，如果不是最终状态就不用执行
                $sp_config = sp_model::get_sp_config($c2_task_info['nns_org_id'], $c2_task_info['nns_type'] . '_' . $c2_task_info['nns_action']);
                $q_report_task = $this->is_succ_state($sp_config, $c2_task_info);
                //如果同等片源下的删除	放过 cdn_import_media_sort同分集片源注入排序方式【0或则不设置按照列队排序，1先添加再删除，保证EPG无缝注入】
                if (isset($sp_conf['cdn_import_media_sort']) && (int)$sp_conf['cdn_import_media_sort'] === 1 && $task_info['nns_type'] == BK_OP_MEDIA && $task_info['nns_action'] == BK_OP_DELETE)
                {
                    //该分集下是否有片源不为删除状态，并还未执行完毕
                    $is_index_in_media = $this->op_queue->get_index_status($db, $sp_id, $task_info['nns_index_id'], $task_info['nns_media_id']);
                    if ($is_index_in_media > 0)
                    {
                        //新增同等片源下，如果C2中无同一片源的新增，则删除此删除队列
                        if (empty($c2_task_info) || $c2_task_info === false)
                        {
                            //echo 'c2 is empty task';
                            //echo "<br/>";
                        } else
                        {
                            //echo 'have media add cdn ,this action continue';
                            //echo "<br/>";
                            continue;
                        }
                    }
                }
                //如果片源的操作是注入失败的，那么就默认这个操作已经完成
                // if(is_array($c2_task_info)&&$c2_task_info!=null){
                // if($c2_task_info['nns_type']==BK_OP_MEDIA&&$c2_task_info['nns_status']==-1&&$c2_task_info['nns_type']==BK_OP_MEDIA){
                // if($task_info['nns_id']!=$c2_task_info['nns_op_id']){
                // $this->op_queue->task_ok($db, $c2_task_info['nns_op_id']);
                // $q_report_task=true;
                // }
//
                // }
                // }
                $task_info['nns_message_id'] = (isset($task_info['nns_message_id']) && strlen($task_info['nns_message_id']) > 0) ? $task_info['nns_message_id'] : '';
                //var_dump($q_report_task);
                //c2任务表中存在不为终态的该任务
                if ($q_report_task === false)
                {

                    //echo '2--';
                    //echo "<br/>";
                    //if($c2_task_info!=-1){
                    if (is_array($c2_task_info) && $c2_task_info != null)
                    {
                        continue;
                        //修改操作id,状态
                        if ($task_info['nns_id'] != $c2_task_info['nns_op_id'])
                        {
                            //如果存在分组标示 上面的数据要一直存在队列中 等待下面的数据处理完毕才下发下去
                            if ($task_info['nns_is_group'] != 0)
                            {
                                $temp_millisecond = round(np_millisecond_f() * 1000);
                                nl_execute_by_db("update nns_mgtvbk_op_queue set nns_op_mtime='{$temp_millisecond}' where nns_id='{$task_info['nns_id']}'", $db);
                                continue;
                            }
                            $set = "";
                            //存在任意一状态为终态，修改状态为等待注入
                            if ($c2_task_info['nns_status'] == 7 || $c2_task_info['nns_epg_status'] == 100)
                            {
                                $set = ",nns_status=1,nns_epg_status=97";
                            }
                            nl_execute_by_db("update nns_mgtvbk_c2_task set nns_cp_id='{$str_c2_nns_cp_id}',nns_message_id='{$task_info['nns_message_id']}',nns_name='{$task_info['nns_name']}', nns_op_id='{$task_info['nns_id']}' $set where nns_id='{$c2_task_info['nns_id']}'", $db);
                            $this->op_queue->task_ok($db, $c2_task_info['nns_op_id']);
                            $c2_task_info['nns_op_id'] = $task_info['nns_id'];
                        }
                    }
                    //continue;
                    //}
                }


                //查询切片的任务的ID  便于获取切片之后的地址
                //<update zhiyong.luo 2016-03-22 此处暂无用处，屏蔽>
//					$clip_task_id = "";
//					$clip_task_date = "";
//					if($task_info['nns_type']==BK_OP_MEDIA){
//
//						//获取切片信息
//						$clip_info = nl_db_get_one("select * from nns_mgtvbk_clip_task where nns_org_id='$sp_id' and nns_video_index_id='$nns_parent_id' and nns_video_media_id='$nns_ref_id' and nns_op_id='{$task_info['nns_id']}'  order by nns_create_time desc limit 1", $db);
//						if(is_array($clip_info)&&$clip_info!=null){
//							$clip_task_id = $clip_info['nns_id'];
//							$clip_task_date = $clip_info['nns_date'];
//						}
//
//						if(isset($task_info['nns_ex_data']['clip_id'])){
//							$clip_task_id = $task_info['nns_ex_data']['clip_id'];
//						}
//
//						if(isset($task_info['nns_ex_data']['clip_date'])){
//							$clip_task_date = $task_info['nns_ex_data']['clip_date'];
//						}
//
//
//
//					}
                $c2_task_id = "";
                $is_new_data = false;
                //如果注入进来的删除命令，而且c2中又没有这个记录，并且中心同步删除指令生成c2虚拟任务开关关闭，则忽略
                if (($c2_task_info === false || empty($c2_task_info)) && (int)$sp_conf['virtual_destroy_task'] === 0)
                {
                    //如果注入进来的删除命令，而c2中又没有这个记录  则忽略
                    if ($task_info['nns_action'] == BK_OP_DELETE)
                    {

                        $this->op_queue->task_progress($db, $task_info['nns_id']);
                        $this->op_queue->task_ok($db, $task_info['nns_id'], $task_info, false);
                        //echo '3--';
                        //echo "<br/>";
                        continue;
                    }
                }
                //如果存在任务就修改它的动作
                if (is_array($c2_task_info) && $c2_task_info != null)
                {
                    //echo '4--';
                    //echo "<br/>";
                    //如果列队过来的是添加动作，而C2任务中的是添加或则修改，则将c2设置为修改
                    if (($c2_task_info['nns_action'] == BK_OP_MODIFY || $c2_task_info['nns_action'] == BK_OP_ADD) && $task_info['nns_action'] == BK_OP_ADD && ((int)$c2_task_info['nns_status'] != 7 || (int)$c2_task_info['nns_epg_status'] != 100))
                    {
                        if ($q_report_task)
                        {
                            $task_info['nns_action'] = BK_OP_MODIFY;
                            //$task_info['nns_action'] = BK_OP_ADD;
                        } else
                        {
                            $task_info['nns_action'] = BK_OP_ADD;
                        }

                    }

                    //如果c2中本身是删除，而任务列队中同步的操作是添加或则修改，则按照新增处理
                    if ($c2_task_info['nns_action'] == BK_OP_DELETE && ($task_info['nns_action'] == BK_OP_MODIFY || $task_info['nns_action'] == BK_OP_ADD))
                    {
                        $task_info['nns_action'] = BK_OP_ADD;
                        //echo '6--';
                        //echo "<br/>";
                    }

                    //如果过来的删除炒作
                    //如果操作列队里的状态和记录表里的状态一样，则判断c2的状态是不是最终状态，如果是最终状态，则忽略，并且将操作列队的状态设置 OK
                    //if($task_info['nns_action']==BK_OP_DELETE&&$c2_task_info['nns_action']==BK_OP_DELETE){
                    //$this->op_queue->task_progress($db, $task_info['nns_id']);
                    //nl_execute_by_db("update nns_mgtvbk_c2_task set nns_modify_time=now(),nns_name='{$task_info['nns_name']}',nns where nns_id='{$c2_task_info['nns_id']}'", $db);
                    //$this->op_queue->task_ok($db, $task_info['nns_id']);
                    //echo '7--';echo "<br/>";
                    //continue;
                    //}


                    //

                    //如果主媒资或者分集队列的操作是删除，则将它的所有子级正在执行的状态设置为cancel
                    if (($task_info['nns_type'] == BK_OP_VIDEO || $task_info['nns_type'] == BK_OP_INDEX) && $task_info['nns_action'] == BK_OP_DELETE)
                    {
                        //echo '8--';
                        //echo "<br/>";
                        $this->__set_child_cancel($sp_id, $task_info['nns_type'], $c2_task_info['nns_ref_id']);
                    }
                    //修改状态和动作
                    $sql_c2task = "update nns_mgtvbk_c2_task  set nns_epg_fail_time=0,nns_cdn_fail_time=0,nns_cp_id='{$str_c2_nns_cp_id}',nns_is_group='{$int_nns_is_group}',nns_weight='{$int_nns_weight}',nns_message_id='{$task_info['nns_message_id']}',nns_status=" . SP_C2_WAIT . ",nns_action='{$task_info['nns_action']}',nns_modify_time=now(),nns_op_id='{$task_info['nns_id']}',nns_epg_status=" . SP_EPG_WAIT . ",nns_name='{$task_info['nns_name']}' where nns_id='{$c2_task_info['nns_id']}'";
                    //如果是片源
                    if ($task_info['nns_type'] == BK_OP_MEDIA)
                    {
                        $ex_data = "";
                        //非删除指令，修改信息
                        if ($task_info['nns_action'] != BK_OP_DELETE)
                        {
                            //if(isset($sp_conf['before_execute_sp'])&&!empty($sp_conf['before_execute_sp'])&&$task_info['nns_action']!=BK_OP_DELETE){
                            $exdata = $task_info['nns_ex_data'];
                            if (isset($exdata['url']))
                            {
                                $ex_data .= " ,nns_file_path='" . $exdata['url'] . "' ";
                            }
                            if (isset($exdata['clip_id']))
                            {
                                $ex_data .= " ,nns_clip_task_id='" . $exdata['clip_id'] . "' ";
                            }
                            if (isset($exdata['clip_date']))
                            {
                                $ex_data .= " ,nns_clip_date='" . $exdata['clip_date'] . "' ";
                            }
                            if (isset($exdata['size']))
                            {
                                $ex_data .= " ,nns_file_size='" . $exdata['size'] . "' ";
                            }
                            if (isset($exdata['file_md5']))
                            {
                                $ex_data .= " ,nns_file_md5='" . $exdata['file_md5'] . "' ";
                            }
                            if (isset($exdata['policy']))
                            {
                                $ex_data .= " ,nns_cdn_policy='" . $exdata['policy'] . "' ";
                            }
                            if (isset($task_info['nns_message_id']) && strlen($task_info['nns_message_id']) > 0)
                            {
                                $ex_data .= " ,nns_message_id='" . $task_info['nns_message_id'] . "' ";
                            }

                        }
                        $sql_c2task = "update nns_mgtvbk_c2_task  set nns_epg_fail_time=0,nns_cdn_fail_time=0,nns_cp_id='{$str_c2_nns_cp_id}',nns_weight='{$int_nns_weight}',nns_is_group='{$int_nns_is_group}',nns_status=" . SP_C2_WAIT . ",nns_action='{$task_info['nns_action']}',nns_modify_time=now(),nns_op_id='{$task_info['nns_id']}',nns_epg_status=" . SP_EPG_WAIT . ",nns_name='{$task_info['nns_name']}' $ex_data where nns_id='{$c2_task_info['nns_id']}'";
                    }
                    $c2_task_id = $c2_task_info['nns_id'];

                } //如果注入进来的删除命令，而且c2中又没有这个记录，并且中心同步删除指令生成c2虚拟任务开关打开，则生成虚拟c2任务
                elseif (!is_array($c2_task_info) && $c2_task_info === null && $task_info['nns_action'] == BK_OP_DELETE && (int)$sp_conf['virtual_destroy_task'] === 1)
                {
                    //echo '7--';
                    //echo "<br/>";
                    $id = np_guid_rand($sp_id);
                    $sql_c2task = "insert into nns_mgtvbk_c2_task(nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_src_id,nns_clip_task_id,nns_clip_date,nns_op_id,nns_epg_status,nns_message_id,nns_is_group,nns_weight,nns_cp_id) values ('$id','{$task_info['nns_type']}','{$task_info['nns_name']}','$nns_ref_id','" . BK_OP_DELETE . "'," . SP_C2_WAIT . ",now(),'$sp_id','$nns_parent_id',null,null,'{$task_info['nns_id']}'," . SP_EPG_WAIT . ",'{$task_info['nns_message_id']}','{$int_nns_is_group}','{$int_nns_weight}','{$str_c2_nns_cp_id}')";
                } else
                {
                    //echo '9--';
                    //echo "<br/>";

                    //如果获取的操作队列动作为删除或者c2没有注入，则将转台修改为添加
                    $id = np_guid_rand($sp_id);

                    $sql_c2task = "insert into nns_mgtvbk_c2_task(nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_src_id,nns_clip_task_id,nns_clip_date,nns_op_id,nns_epg_status,nns_message_id,nns_is_group,nns_weight,nns_cp_id) values ('$id','{$task_info['nns_type']}','{$task_info['nns_name']}','$nns_ref_id','" . BK_OP_ADD . "'," . SP_C2_WAIT . ",now(),'$sp_id','$nns_parent_id',null,null,'{$task_info['nns_id']}'," . SP_EPG_WAIT . ",'{$task_info['nns_message_id']}','{$int_nns_is_group}','{$int_nns_weight}','{$str_c2_nns_cp_id}')";
                    $ex_data_filter = "";
                    $ex_data_filter_value = "";
                    if ($task_info['nns_type'] == BK_OP_MEDIA)
                    {
                        if ($task_info['nns_action'] != BK_OP_DELETE)
                        {
                            //if(isset($sp_conf['before_execute_sp'])&&!empty($sp_conf['before_execute_sp'])&&$task_info['nns_action']!=BK_OP_DELETE){
                            $exdata = $task_info['nns_ex_data'];
                            //$ex_data_filter = ",nns_file_path,nns_clip_task_id,nns_clip_date,nns_file_size,nns_file_md5,nns_cdn_policy";
                            //$ex_data_filter_value = " ,'".$exdata['url']."','".$exdata['clip_id']."' ,'".$exdata['clip_date']."','".$exdata['size']."' ,'".$exdata['file_md5']."','".$exdata['policy']."'";
                            if (isset($exdata['url']))
                            {
                                $ex_data_filter .= ",nns_file_path";
                                $ex_data_filter_value .= ",'" . $exdata['url'] . "'";
                            }
                            if (isset($exdata['clip_id']))
                            {
                                $ex_data_filter .= ",nns_clip_task_id";
                                $ex_data_filter_value .= ",'" . $exdata['clip_id'] . "'";
                            }
                            if (isset($exdata['clip_date']))
                            {
                                $ex_data_filter .= ",nns_clip_date";
                                $ex_data_filter_value .= ",'" . $exdata['clip_date'] . "'";
                            }
                            if (isset($exdata['size']))
                            {
                                $ex_data_filter .= ",nns_file_size";
                                $ex_data_filter_value .= ",'" . $exdata['size'] . "'";
                            }
                            if (isset($exdata['file_md5']))
                            {
                                $ex_data_filter .= ",nns_file_md5";
                                $ex_data_filter_value .= ",'" . $exdata['file_md5'] . "'";
                            }
                            if (isset($exdata['policy']))
                            {
                                $ex_data_filter .= ",nns_cdn_policy";
                                $ex_data_filter_value .= ",'" . $exdata['policy'] . "'";
                            }
                        }
                        if (isset($task_info['nns_message_id']) && strlen($task_info['nns_message_id']) > 0)
                        {
                            $ex_data_filter .= ",nns_message_id";
                            $ex_data_filter_value .= ",'" . $task_info['nns_message_id'] . "'";
                        }
                        $sql_c2task = "insert into nns_mgtvbk_c2_task(nns_cp_id,nns_weight,nns_is_group,nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_src_id,nns_op_id,nns_epg_status" . $ex_data_filter . ") values ('{$str_c2_nns_cp_id}','{$int_nns_weight}','{$int_nns_is_group}','$id','{$task_info['nns_type']}','{$task_info['nns_name']}','$nns_ref_id','" . BK_OP_ADD . "'," . SP_C2_WAIT . ",now(),'$sp_id','$nns_parent_id','{$task_info['nns_id']}','" . SP_EPG_WAIT . "'" . $ex_data_filter_value . ")";
                    }
                    $c2_task_id = $id;
                    $is_new_data = true;
                }
                //echo $sql_c2task;
                $result = nl_execute_by_db($sql_c2task, $db);

                //var_dump($result);
                //插入成功	 修改列队状态
                if ($result)
                {
                    if ($task_info['nns_type'] == BK_OP_MEDIA && $task_info['nns_action'] == BK_OP_DELETE && (int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
                    {
                        //如果是删除命令，并且是片源，就需要将切片里面的切片日志记录删除掉
                        $update_clip_state = "update nns_mgtvbk_clip_task set nns_state='cancel',nns_task_name='{$task_info['nns_name']}' where nns_org_id='$sp_id' and nns_video_id='{$task_info['nns_video_id']}' and nns_video_index_id='{$task_info['nns_index_id']}' and nns_video_media_id='{$task_info['nns_media_id']}'";
                        nl_execute_by_db($update_clip_state, $db);
                    }
                    //添加计数+1

                    if ($task_info['nns_type'] == 'video')
                    {
                        $num_video++;
                    } elseif ($task_info['nns_type'] == 'index')
                    {
                        $num_index++;
                    } elseif ($task_info['nns_type'] == 'media')
                    {
                        $num_media++;
                    }

                    //$this->op_queue->task_progress($db, $sp_id, $nns_ref_id, $task_info['nns_type']);
                    $this->op_queue->task_progress($db, $task_info['nns_id']);
                }
                //echo "task_end-".date('Y-m-d H:i:s')."<br/>";
                //echo PHP_EOL;
                //echo "RunTime:" . np_runtime_ex('task' . $task_info['nns_id'], true);
                //echo PHP_EOL;
            }
        }
    }


    public function __destruct()
    {
        unset($this->op_queue, $this->db);

    }

    /**
     * 获取操作列队的数据
     */
    public function get_q_task_detail($op_id)
    {
        $result = array();
        $db = nn_get_db(NL_DB_READ);
        $db->open();
        $sql = "select * from nns_mgtvbk_op_queue where nns_id='$op_id'";
        $task_info = nl_db_get_one($sql, $db);
        $result['q_task_info'] = $task_info;
        if ($task_info['nns_type'] == 'media')
        {
            //
            $sql = "select * from nns_vod_media where nns_id='{$task_info['nns_media_id']}'";
            $result['media_info'] = nl_db_get_one($sql, $db);
        } else if ($task_info['nns_type'] == 'index')
        {
            //
            $sql = "select * from nns_vod_index where nns_id='{$task_info['nns_index_id']}'";
            $result['index_info'] = nl_db_get_one($sql, $db);
        } else if ($task_info['nns_type'] == 'video')
        {
            //
            $sql = "select * from nns_vod where nns_id='{$task_info['nns_video_id']}'";
            $result['video_info'] = nl_db_get_one($sql, $db);
        }
        return $result;
    }

    //获取黑名单
    private function __get_is_black($sp_id = null, $is_black = 1, $asset_id = null, $category_id = null)
    {
        $db = nn_get_db(NL_DB_READ);
        $db->open();
        $sql = "select * " .
            "from nns_mgtvbk_op_blacklist  where 1=1 ";
        $wh_arr = array();
        $wh_arr[] = " nns_is_black='" . $is_black . "'";
        //if(empty($sp_id)){
        //$wh_arr[] = " nns_is_black='".$is_black."'";
        //}
        if (!empty($sp_id))
        {
            $wh_arr[] = " nns_org_id='$sp_id'";
        }

        if (!empty($asset_id))
        {
            $wh_arr[] = " nns_video_id='$asset_id'";
        }
        if (!empty($category_id))
        {
            $wh_arr[] = " nns_category_id='$category_id'";
        }
        if (!empty($wh_arr))
        {
            $sql .= " and " . implode(" and ", $wh_arr);
        }

        $data = nl_db_get_all($sql, $db);

        return $data;
    }

    /**
     *
     * 黑白名单列表获取
     * sp_id string
     * $filter array 查询条件
     *
     */
    public function get_black_list($sp_id, $filter = null, $start = 0, $size = 100)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_READ);
        $sql = "select * " .
            "from nns_mgtvbk_op_blacklist  where nns_org_id='$sp_id'";
        if ($filter != null)
        {
            $wh_arr = array();
            if (!empty($filter['nns_name']))
            {
                $wh_arr[] = " nns_name like '%" . $filter['nns_name'] . "%'";
            }
            if (!empty($filter['nns_type']))
            {
                $wh_arr[] = " nns_type='" . $filter['nns_type'] . "'";
            }
            if (!empty($filter['nns_is_black']))
            {
                if ($filter['nns_is_black'] == 11)
                {
                    $filter['nns_is_black'] = 1;
                } else
                {
                    $filter['nns_is_black'] = 0;
                }
                $wh_arr[] = " nns_is_black='" . $filter['nns_is_black'] . "'";
            }
            if (!empty($filter['nns_category_id']))
            {
                $wh_arr[] = " nns_category_id='" . $filter['nns_category_id'] . "'";
            }
            if (!empty($wh_arr)) $sql .= " and " . implode(" and ", $wh_arr);
        }
        $count_sql = $sql;
        $count_sql = str_replace('*', ' count(*) as temp_count ', $count_sql);
        $sql .= " order by nns_create_time desc ";
        $sql .= " limit $start,$size";
        $data = nl_db_get_all($sql, $db);
        $rows = nl_db_get_col($count_sql, $db);
        return array('data' => $data, 'rows' => $rows);
    }

    public function del_blacklist($sp_id, $params)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $ids = explode(',', $params);
        foreach ($ids as $id)
        {
            if (empty($id))
            {
                continue;
            }
            nl_execute_by_db("delete from nns_mgtvbk_op_blacklist where nns_id='{$id}'", $db);
        }

        return true;
    }

    /**
     *
     * 影片绑定黑白名单
     * $params = array('nns_id'=>'资源库Id',nns_type='名单类型','nns_is_black'=>true/false);
     * 黑名单：1
     * 白名单：0
     */
    public function add_blacklist($sp_id, $params, $is_black)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $ids = explode(',', $params);
        foreach ($ids as $id)
        {
            if (empty($id))
            {
                continue;
            }
            $vod_info = video_model::get_vod_info($id);


            //print_r($vod_info);

            //nns_mgtvbk_op_blacklist

            $abs = abs($is_black - 1);

            $sql = "select * from nns_mgtvbk_op_blacklist where nns_org_id='" . $sp_id . "' and nns_type='1' and nns_video_id='" . $id . "' and nns_is_black='" . $abs . "'";

            $info = nl_db_get_one($sql, $db);

            if (is_array($info) && $info != null)
            {
                continue;
            }


            $sql = "select * from nns_mgtvbk_op_blacklist where nns_org_id='" . $sp_id . "' and nns_type='1' and nns_video_id='" . $id . "' and nns_is_black='" . $is_black . "'";

            $info = nl_db_get_one($sql, $db);

            if (is_array($info) && $info != null)
            {
                continue;
            }

            $data = array(
                'nns_id' => np_guid_rand(),
                'nns_name' => $vod_info['nns_name'],
                'nns_video_id' => $id,
                'nns_type' => 1,
                'nns_org_id' => $sp_id,
                'nns_create_time' => date('Y-m-d H:i:s'),
                'nns_is_black' => $is_black
            );
            nl_db_insert($db, 'nns_mgtvbk_op_blacklist', $data);
        }

    }

    /**
     * @通过审核
     * ids opid
     */
    public function update_queue_audit($ids)
    {
        //$db = audit($db,$op_id)
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $opid_arr = explode(',', $ids);
        foreach ($opid_arr as $op_id)
        {
            $this->op_queue->audit($db, $op_id);
        }
        return true;
    }

    /**
     * 获取任务名称
     * @param string $video_id 视频id
     * @param string $video_type 视频类型
     * @return string task_name
     * @author yunping.yang
     * @date 2014-8-12
     */
    private function get_task_name($video_id, $video_type)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        //获取任务名称
        $task_name = '';
        $asset_id = '';
        $nns_kbps = 0;
        $nns_cp_id = '';
        $nns_ext_url = '';
        $nns_url = '';
        $nns_live_to_media = 1;
        $nns_filetype = '';
        $ex_data = array();
        switch ($video_type)
        {
            case BK_OP_VIDEO:
                $task_name_arr = nl_db_get_one("select nns_name,nns_cp_id,nns_asset_import_id,nns_ext_url from nns_vod where nns_id='{$video_id}'", $db);
                $task_name = $task_name_arr['nns_name'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $asset_id = $video_id;
                $str_import_id = $task_name_arr['nns_asset_import_id'];
                $nns_ext_url = $task_name_arr['nns_ext_url'];
                $nns_media_encode_flag = 0;
                $nns_ext_info = '';
                $nns_tag = '';
                break;
            case BK_OP_INDEX:
                $task_name_arr = nl_db_get_one("select nns_name,nns_vod_id,nns_index,nns_cp_id,nns_import_id,nns_ext_url from nns_vod_index where nns_id='{$video_id}'", $db);
                if (strlen(trim($task_name_arr['nns_name'])) <= 0)
                {
                    $task_name_arr['nns_index1'] = (int)$task_name_arr['nns_index'] + 1;
                    $task_name_arr['nns_name'] = '第' . $task_name_arr['nns_index1'] . '集';
                }
                $task_name = '[' . $task_name_arr['nns_name'] . ']';
                $asset_id = $task_name_arr['nns_vod_id'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $str_import_id = $task_name_arr['nns_import_id'];
                $nns_ext_url = $task_name_arr['nns_ext_url'];
                $nns_media_encode_flag = 0;
                $nns_ext_info = '';
                $nns_tag = '';
                break;
            case BK_OP_MEDIA:
                $task_name_arr = nl_db_get_one("select vodindex.nns_name,vodindex.nns_index,media.nns_mode,media.nns_filetype,media.nns_tag as nns_tag,media.nns_media_type as nns_media_type,media.nns_url as nns_url,media.nns_vod_id as nns_vod_id,media.nns_kbps as nns_kbps,media.nns_cp_id as nns_cp_id,media.nns_content_id as nns_content_id,media.nns_import_id as nns_import_id,media.nns_ext_url as nns_ext_url,media.nns_ext_info as nns_ext_info,media.nns_encode_flag as nns_encode_flag  from nns_vod_media media left join nns_vod_index vodindex on media.nns_vod_index_id=vodindex.nns_id   where media.nns_id='{$video_id}'", $db);
                if (strlen(trim($task_name_arr['nns_name'])) <= 0)
                {
                    $task_name_arr['nns_index1'] = (int)$task_name_arr['nns_index'] + 1;
                    $task_name_arr['nns_name'] = '第' . $task_name_arr['nns_index1'] . '集';
                }
                $ex_data['nns_content_id'] = $task_name_arr['nns_content_id'];
                $asset_id = $task_name_arr['nns_vod_id'];
                $nns_kbps = ($task_name_arr['nns_kbps'] > 0) ? $task_name_arr['nns_kbps'] : 0;
                $task_name = '[' . $task_name_arr['nns_name'] . '] [' . $nns_kbps . '/kbps] ' . ' [' . $task_name_arr['nns_tag'] . '] ' . $task_name_arr['nns_mode'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $str_import_id = $task_name_arr['nns_import_id'];
                $nns_ext_url = $task_name_arr['nns_ext_url'];
                $nns_ext_info = $task_name_arr['nns_ext_info'];
                $nns_tag = (strlen($task_name_arr['nns_tag']) > 0) ? $task_name_arr['nns_tag'] : '';
                $nns_media_encode_flag = (isset($task_name_arr['nns_encode_flag']) && in_array($task_name_arr['nns_encode_flag'], array('0', '1', '2'))) ? $task_name_arr['nns_encode_flag'] : 0;
                $nns_tag = $task_name_arr['nns_tag'];
                $nns_url = $task_name_arr['nns_url'];
                $nns_filetype = $task_name_arr['nns_filetype'];
                $nns_live_to_media = $task_name_arr['nns_media_type'];
                break;
            case BK_OP_LIVE:
                $task_name_arr = nl_db_get_one("select nns_name,nns_cp_id,nns_import_id,nns_integer_id from nns_live where nns_id='{$video_id}'", $db);
                $task_name = $task_name_arr['nns_name'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $asset_id = $video_id;
                $str_import_id = (strlen($task_name_arr['nns_import_id']) > 0) ? $task_name_arr['nns_import_id'] : $task_name_arr['nns_integer_id'];
                $nns_ext_url = '';
                $nns_media_encode_flag = 0;
                $nns_ext_info = '';
                $nns_tag = '';
                break;
            case BK_OP_LIVE_MEDIA:
                $task_name_arr = nl_db_get_one("select live_index.nns_index,media.nns_mode,media.nns_live_id as nns_vod_id,media.nns_tag as nns_tag,media.nns_kbps as nns_kbps,media.nns_cp_id as nns_cp_id,media.nns_content_id as nns_content_id,media.nns_ext_url as nns_ext_url  from nns_live_media as media left join nns_live_index live_index on media.nns_live_index_id=live_index.nns_id   where media.nns_id='{$video_id}'", $db);
                if (strlen(trim($task_name_arr['nns_name'])) <= 0)
                {
                    $task_name_arr['nns_index1'] = (int)$task_name_arr['nns_index'] + 1;
                    $task_name_arr['nns_name'] = '第' . $task_name_arr['nns_index1'] . '集';
                }
                $ex_data['nns_content_id'] = $task_name_arr['nns_content_id'];
                $asset_id = $task_name_arr['nns_vod_id'];
                $nns_kbps = ($task_name_arr['nns_kbps'] > 0) ? $task_name_arr['nns_kbps'] : 0;
                $task_name = '[' . $task_name_arr['nns_name'] . '] [' . $nns_kbps . '/kbps] ' . ' [' . $task_name_arr['nns_tag'] . '] ' . $task_name_arr['nns_mode'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $str_import_id = $task_name_arr['nns_content_id'];
                $nns_ext_url = $task_name_arr['nns_ext_url'];
                $nns_media_encode_flag = 0;
                $nns_ext_info = '';
                $nns_tag = '';
                break;
            case BK_OP_PLAYBILL:
                $task_name_arr = nl_db_get_one("select nns_name,nns_cp_id,nns_playbill_import_id,nns_ext_url,nns_begin_time,nns_live_id from nns_live_playbill_item where nns_id='{$video_id}'", $db);
                if (isset($task_name_arr['nns_live_id']) && strlen($task_name_arr['nns_live_id']))
                {
                    $task_name_arr_live = nl_db_get_one("select nns_name from nns_live where nns_id='{$task_name_arr['nns_live_id']}'", $db);
                }
                $live_name_temp = isset($task_name_arr_live['nns_name']) ? $task_name_arr_live['nns_name'] : '';
                $task_name = $live_name_temp . '] [' . $task_name_arr['nns_begin_time'] . '] [' . $task_name_arr['nns_name'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $asset_id = $video_id;
                $str_import_id = $task_name_arr['nns_playbill_import_id'];
                $nns_ext_url = $task_name_arr['nns_ext_url'];
                $nns_media_encode_flag = 0;
                $nns_ext_info = '';
                $nns_tag = '';
                break;
            case BK_OP_FILE:
                $task_name_arr = nl_db_get_one("select nns_name,nns_cp_id,nns_import_id,nns_ext_url from nns_file_package where nns_id='{$video_id}'", $db);
                $task_name = $task_name_arr['nns_name'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $asset_id = $video_id;
                $str_import_id = $task_name_arr['nns_import_id'];
                $nns_ext_url = $task_name_arr['nns_ext_url'];
                $nns_ext_info = '';
                $nns_media_encode_flag = 0;
                $nns_tag = '';
                break;
            case BK_OP_PRODUCT:
                $task_name_arr = nl_db_get_one("select nns_order_name as nns_name,nns_cp_id,nns_order_number as nns_import_id from nns_product where nns_id='{$video_id}'", $db);
                $task_name = $task_name_arr['nns_name'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $asset_id = $video_id;
                $str_import_id = $task_name_arr['nns_import_id'];
                $nns_ext_url = '';
                $nns_ext_info = '';
                $nns_media_encode_flag = 0;
                $nns_tag = '';
                break;
            case  BK_OP_SEEKPOINT:
                $task_name_arr = nl_db_get_one("select * from nns_vod_index_seekpoint where nns_id='{$video_id}'", $db);
                $task_name = $task_name_arr['nns_name'];
                $nns_cp_id = (strlen($task_name_arr['nns_cp_id']) > 0) ? $task_name_arr['nns_cp_id'] : 0;
                $asset_id = $video_id;
                $str_import_id = $task_name_arr['nns_import_id'];
                $nns_ext_url = '';
                $nns_ext_info = '';
                $nns_media_encode_flag = 0;
                $nns_tag = '';
                break;
        }
        if ($video_type == BK_OP_VIDEO || $video_type == BK_OP_PLAYBILL || $video_type == BK_OP_FILE || $video_type == BK_OP_LIVE)
        {
            $task_name = '[' . $task_name . ']';
        } else if ($video_type == BK_OP_LIVE_MEDIA)
        {
            $video_name = nl_db_get_col("select nns_name from nns_live where nns_id='{$asset_id}'", $db);
            $task_name = '[' . $video_name . '] ' . $task_name;
        } else
        {
            $video_name = nl_db_get_col("select nns_name from nns_vod where nns_id='{$asset_id}'", $db);
            $task_name = '[' . $video_name . '] ' . $task_name;
        }
        $array = array(
            'task_name' => $task_name,
            'asset_id' => $asset_id,
            'nns_kbps' => $nns_kbps,
            'cp_id' => $nns_cp_id,
            'ex_data' => $ex_data,
            'import_id' => $str_import_id,
            'nns_ext_url' => $nns_ext_url,
            'nns_ext_info' => $nns_ext_info,
            'nns_media_encode_flag' => $nns_media_encode_flag,
            'nns_tag' => $nns_tag,
            'nns_url' => $nns_url,
            'nns_live_to_media' => $nns_live_to_media,
            'nns_filetype' => $nns_filetype,
        );
 		/*print_r($array);die;*/
        return $array;
    }

    /**
     * 添加上下线队列数据
     * @param string $video_id 影片id
     * @param string $video_type 影片类型
     * @param string $action 操作行为 online  | unline
     * @param string $message_id 消息id
     * @param string $import_id 注入id
     * @param string $order 排序
     * @param string $cp_id cp_id
     * @param string $category_id 栏目id
     * @param string $asset_type 媒资类型
     * @author liangpan
     * @date 2015-11-26
     */
    public function q_add_unline_op_mgtv($video_id, $video_type, $action, $message_id, $import_id, $order, $cp_id, $category_id = '1000', $asset_type = 'video', $bk_cp_id = '', $asset_id)
    {
        set_time_limit(0);
        //获取任务名称
        $task_arr = $this->get_task_name($video_id, $video_type);
        $task_name = $task_arr['task_name'];
        $this->dc = nl_get_dc(array(
            "db_policy" => NL_DB_WRITE,
            "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        if (!empty($bk_cp_id))
        {
            $cp_id = $bk_cp_id;
        }
        //$sp_list_sql = "select * from nns_mgtvbk_sp";
        //根据CP查询绑定的SP
        $arr_sp = nl_sp::query($this->dc, array('like' => array('nns_bind_cp' => $cp_id)));
        if (!is_array($arr_sp['data_info']) || empty($arr_sp['data_info']))
        {
            return array('ret' => 1, 'reason' => '没有查询到相关cp绑定关系，cp_id为:' . $cp_id);
        }
        $temp_array = array();
        foreach ($arr_sp['data_info'] as $sp_val)
        {
            $sp_config = json_decode($sp_val['nns_config'], true);
            //检查媒资上下线开关是否开启  如果未开启 直接continue
            if (!isset($sp_config['online_disabled']) || $sp_config['online_disabled'] != 1)
            {
                $temp_array[] = 'video_id为：' . $video_id . ';SP_ID为:' . var_export($sp_val, true) . '的上下线开关未开启,值为' . $sp_config['online_disabled'];
                continue;
            }

            $online_disabled = (isset($sp_config['online_audit']) && in_array($sp_config['online_audit'], array(0, 1, 2))) ? $sp_config['online_audit'] : 1;
            $nns_audit = 0;
            //0 为进入媒资上下线为自动审核通过，1 为审核不通过，2为下线审核不通过/上线自动审核通过
            if ($action == 'online')
            {
                if ($online_disabled == '0' || $online_disabled == '2')
                {
                    $nns_audit = 1;
                }
            } else if ($action == 'unline')
            {
                if ($online_disabled == '0')
                {
                    $nns_audit = 1;
                }
            } else
            {
                $temp_array[] = 'video_id为：' . $video_id . ';SP_ID为:' . $sp_val . '的操作行为为:' . $action . ',但是只有online、unline可走逻辑';
                continue;
            }
            $in_params = array(
                'nns_vod_id' => $video_id,
                'nns_message_id' => $message_id,
                'nns_video_name' => $task_name,
                'nns_import_id' => $import_id,
                'nns_category_id' => $category_id,
                'nns_order' => $order,
                'nns_action' => $action,
                'nns_cp_id' => $cp_id,
                'nns_org_id' => $sp_val['nns_id'],
                'nns_status' => '1',
                'nns_audit' => $nns_audit,
                'nns_fail_time' => '0',
                'nns_delete' => '0',
                'nns_type' => $asset_type,
                'nns_asset_id' => $asset_id,
            );
            //检查当前队列中是否存在 等待注入
            $wait_params = array(
                'nns_import_id' => $import_id,
                'nns_category_id' => $category_id,
                'nns_org_id' => $sp_val['nns_id'],
                'nns_cp_id' => $cp_id,
                'nns_status' => '1',
                'nns_type' => $asset_type,
                'nns_asset_id' => $asset_id,
                //'nns_vod_id' => $video_id,
            );
            $wait_re = nl_asset_online::check_online_queue($this->dc, $wait_params);
            if ($wait_re['ret'] != 0)
            {
                return $wait_re;
            }
            if ($wait_re['data_info']['count'] > 0)
            {
                //存在相同媒资等待注入的任务队列，则进行修改
                nl_asset_online::update($this->dc, $in_params, $wait_params);
                unset($in_params);
                unset($wait_params);
                $temp_array[] = 'video_id为：' . $video_id . ';SP_ID为:' . $sp_val . '存在相同媒资等待注入的任务队列，则进行修改';
                continue;
            }
            $fail_params = array(
                'nns_import_id' => $import_id,
                'nns_category_id' => $category_id,
                'nns_org_id' => $sp_val['nns_id'],
                'nns_cp_id' => $cp_id,
                'nns_status' => array(2, 4, 5, 6, 7),
                'nns_type' => $asset_type,
                'nns_asset_id' => $asset_id,
                //'nns_vod_id' => $video_id,
            );
            //检查队列中是否存在  注入失败/反馈失败等任务
            $fail_re = nl_asset_online::check_online_queue($this->dc, $fail_params);
            if ($fail_re['ret'] != 0)
            {
                return $fail_re;
            }
            if ($fail_re['data_info']['count'] > 0)
            {
                //存在则删掉之前的任务
                $resukt_del_by_condition = nl_asset_online::del_by_condition($this->dc, $fail_params);
                if ($resukt_del_by_condition['ret'] != 0)
                {
                    return $resukt_del_by_condition;
                }
                unset($fail_params);
            }
            $result_add = nl_asset_online::add($this->dc, $in_params);

            if ($result_add['ret'] != 0)
            {
                return $result_add;
            }
            unset($in_params);
            unset($sp_config);
        }
        return array('ret' => 0, 'reason' => '上下线注入成功', 'data_info' => $temp_array);
    }

    /**
     * 添加到队列  中心注入指令队列  或则  审核队列
     * @param string $video_id 主媒资id | 分集id | 片源id
     * @param string $video_type 主媒资 video | 分集 index | 片源 media
     * @param string $action add 添加 | modify 修改 | destroy 删除
     * @param string $message_id 运营媒资下发的消息id
     * @param boolean $flag
     * @param $conf_info 通用配置条件数组
     * @author liangpan
     * @date 2015-09-10
     */
    public function q_add_task_op_mgtv($video_id, $video_type, $action, $message_id = null, $flag = true, $conf_info = array(),$arr_import_sp_id=null)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        //获取任务名称
        $task_arr = $this->get_task_name($video_id, $video_type);
        $task_name = $task_arr['task_name'];
        //码率
        $nns_kbps = $task_arr['nns_kbps'];
        //cp_id
        $nns_cp_id = $task_arr['cp_id'];
        $nns_media_encode_flag = (isset($task_arr['nns_media_encode_flag']) && strlen($task_arr['nns_media_encode_flag']) > 0) ? $task_arr['nns_media_encode_flag'] : 0;
        $nns_filetype = (isset($task_arr['nns_filetype']) && strlen($task_arr['nns_filetype']) > 0) ? $task_arr['nns_filetype'] : '';
        $nns_tag = (isset($task_arr['nns_tag']) && strlen($task_arr['nns_tag']) > 0) ? $task_arr['nns_tag'] : '';
        $params = array(
            'nns_video_id' => $video_id,
            'nns_video_type' => $video_type,
            'nns_action' => $action,
            'nns_video_name' => $task_name,
            'nns_cp_id' => $nns_cp_id,
        );
        if ($message_id)
        {
            $params['nns_message_id'] = $message_id;
        }
        $params['nns_op_mtime'] = round(np_millisecond_f() * 1000);
        
        if(isset($arr_import_sp_id) && is_array($arr_import_sp_id) && !empty($arr_import_sp_id))
        {
            $params['nns_op_sp'] = ',' . implode(',', $arr_import_sp_id) . ',';
            $params['nns_create_time'] = date('Y-m-d H:i:s', time());
            $params['nns_id'] = np_guid_rand();
            $params['nns_weight'] = $this->_get_weight();
            $params["nns_is_group"] = $this->_get_is_group();
            nl_db_insert($db, 'nns_mgtvbk_import_op', $params);
            return true;
        }
        
        if (strlen($nns_cp_id) > 0)
        {
            $sql_sp = "select group_concat(nns_id) from nns_mgtvbk_sp where nns_bind_cp like '%,{$nns_cp_id},%' ";
            $sql_cp = "select * from nns_cp where nns_id = '{$nns_cp_id}' limit 1";
            $result_cp = nl_db_get_one($sql_cp, $db);
            if (is_array($result_cp) && isset($result_cp['nns_config']) && !empty($result_cp['nns_config']))
            {
                $arr_cp_config = json_decode($result_cp['nns_config'], true);
                if (is_array($arr_cp_config) && isset($arr_cp_config['message_import_enable']) && $arr_cp_config['message_import_enable'] == '1' && isset($arr_cp_config['message_import_mode']) && $arr_cp_config['message_import_mode'] == '1' && $video_type == 'media')
                {
                    if (isset($task_arr['ex_data']['nns_content_id']) && strlen($task_arr['ex_data']['nns_content_id']) < 1)
                    {
                        return;
                    }
                    include_once dirname(dirname(dirname(__FILE__))) . '/vod_media/vod_media.class.php';
                    $result_vod_media_info = nl_vod_media_v2::query_media_info_by_id($db, $video_id);
                    if (isset($result_vod_media_info['data_info']) && !empty($result_vod_media_info['data_info']))
                    {
                        $str_index_index = $result_vod_media_info['data_info']['index_index'] + 1;
                        $str_media_model = $this->get_media_mode($result_vod_media_info['data_info']['nns_mode']);
                        $result_vod_media_info['data_info']['vod_name'] = $this->str_filter($result_vod_media_info['data_info']['vod_name']);
                        $str_media_name = "{$result_cp['nns_name']}-{$result_vod_media_info['data_info']['vod_name']}第{$str_index_index}集{$str_media_model}";
                        nl_vod_media_v2::edit(null, array('nns_name' => $str_media_name), $video_id, $db);
                    }
                }
            }
        } else
        {
            $sql_sp = "select group_concat(nns_id) from nns_mgtvbk_sp";
        }
        $params['nns_op_sp'] = nl_db_get_col($sql_sp, $db);
        $this->op_sp = explode(',', $params['nns_op_sp']);
        //获取组合配置，通过SP获取SP配置
        if (empty($this->op_sp))
        {
            return;
        }
        $this->excipt_sp_by_media_type($db, $video_type, $nns_media_encode_flag, $nns_tag, $video_id, $nns_filetype);
        if (empty($this->op_sp))
        {
            return;
        }
        $arr_op_sp = $this->op_sp;
        $new_op_sp = array();
        if (!empty($conf_info) && isset($conf_info['import_cdn_mode']) && !empty($conf_info['import_cdn_mode'])) //扩展信息中包含配置信息
        {
            foreach ($this->op_sp as $sp_id)
            {
                $sp_config = sp_model::get_sp_config($sp_id);
                if (isset($sp_config['global_config_bind_key']) && !empty($sp_config['global_config_bind_key'])) //SP绑定了配置信息
                {
                    $gloabl_config_key = rtrim($sp_config['global_config_bind_key'], ",");
                    $gloabl_config_key_arr = explode(",", $gloabl_config_key);
                    $key_value = nl_project_group::get_value_by_ids($db, $gloabl_config_key_arr);
                    if (!is_array($key_value)) //通用配置未配置条件
                    {
                        continue;
                    }
                    if (isset($key_value['import_cdn_mode']))
                    {
                        $del_sp_bool = false;
                        foreach ($key_value['import_cdn_mode'] as $mode)
                        {
                            if ($mode == $conf_info['import_cdn_mode'])
                            {
                                $del_sp_bool = true;//指定SP注入
                                break;
                            }
                        }
                        //湖南zte/hw 删除主媒资和分集操作都会生成队列
                        if(($conf_info['import_cdn_mode']=='zte' || $conf_info['import_cdn_mode']=='hw') && ($video_type=='video' || $video_type=='index') && ($action =='destroy'))
                            {
                                $del_sp_bool = true;
                            }
                        if ($del_sp_bool)
                        {
                            $new_op_sp[] = $sp_id;
                        }
                    }
                }
            }
        }
        if (!empty($new_op_sp))
        {
            $arr_op_sp = $new_op_sp;
        }
        if (empty($arr_op_sp) || !is_array($arr_op_sp))
        {
            return true;
        }
        //添加审核队列
        $this->add_vod_audit($task_name, $video_id, $video_type, $action, $nns_kbps, $flag);
        $params['nns_op_sp'] = ',' . implode(',', $arr_op_sp) . ',';
        $this->op_sp = null;
        $params['nns_create_time'] = date('Y-m-d H:i:s', time());
        $params['nns_id'] = np_guid_rand();
        $params['nns_weight'] = $this->_get_weight();
        $params["nns_is_group"] = $this->_get_is_group();
        nl_db_insert($db, 'nns_mgtvbk_import_op', $params);
    }

    /**
     * 排除 sp的  主媒资分集 片源 配置
     * @param unknown $db
     * @param unknown $video_type
     * @param string $video_id 主媒资id | 分集id | 片源id
     */
    public function excipt_sp_by_media_type($db, $video_type, $media_encode_flag = 0, $nns_tag = '', $video_id = '', $media_filetype = '')
    {
        $result_sp = nl_sp::query_by_ids($db, $this->op_sp);
        if ($result_sp['ret'] != 0)
        {
            return;
        }
        if (!isset($result_sp['data_info']) || empty($result_sp['data_info']) || !is_array($result_sp['data_info']))
        {
            return;
        }
        $result_sp = $result_sp['data_info'];
        $temp_op = array();
        $nns_tag = trim($nns_tag, ',');
        $arr_tag = (strlen($nns_tag) > 0) ? explode(',', $nns_tag) : null;
        $arr_tag = (is_array($arr_tag) && !empty($arr_tag)) ? $arr_tag : null;
        foreach ($result_sp as $sp_val)
        {
            if (!in_array($sp_val['nns_id'], $this->op_sp))
            {
                continue;
            }
            $sp_config = (isset($sp_val['nns_config']) && !empty($sp_val['nns_config'])) ? json_decode($sp_val['nns_config'], true) : null;
            if (isset($sp_config['import_op_enabled']) && (int)$sp_config['import_op_enabled'] === 1)//此SP关闭注入
            {
                continue;
            }
            if (isset($sp_config['op_queue_video_enabled']) && is_array($sp_config['op_queue_video_enabled']) &&
                !empty($sp_config['op_queue_video_enabled']) && !in_array($video_type, $sp_config['op_queue_video_enabled']))
            {
                continue;
            }
            if ($video_type == 'media' && isset($sp_config['op_queue_filetype_enabled']) && is_array($sp_config['op_queue_filetype_enabled']) &&
                !empty($sp_config['op_queue_filetype_enabled']) && !in_array($media_filetype, $sp_config['op_queue_filetype_enabled']))
            {
                continue;
            }
            if ($video_type == 'media' && isset($sp_config['op_queue_media_type_enabled']) && is_array($sp_config['op_queue_media_type_enabled']) &&
                !empty($sp_config['op_queue_media_type_enabled']) && !in_array($media_encode_flag, $sp_config['op_queue_media_type_enabled']))
            {
                continue;
            }
            if ($video_type == 'media' && is_array($arr_tag) && !empty($arr_tag) && isset($sp_config['op_queue_media_tag_enabled']) && is_array($sp_config['op_queue_media_tag_enabled']) &&
                !empty($sp_config['op_queue_media_tag_enabled']))
            {
                $flag = true;
                if (is_array($arr_tag) && !empty($arr_tag))
                {
                    foreach ($arr_tag as $tag_val)
                    {
                        if (in_array($tag_val, $sp_config['op_queue_media_tag_enabled']))
                        {
                            $flag = false;
                            break;
                        }
                    }
                } else
                {
                    $flag = false;
                }
                if ($flag)
                {
                    continue;
                }
            }
            if (isset($sp_config['media_import_op_mode']) && is_array($sp_config['media_import_op_mode']) && !empty($sp_config['media_import_op_mode']) &&
                in_array($sp_val['nns_id'], $this->op_sp) && $video_type === BK_OP_MEDIA)//过滤
            {
                //查询片源信息
                $video_media_info = video_model::get_vod_media_info($video_id);
                if (!is_array($video_media_info) || empty($video_media_info) || in_array($video_media_info['nns_mode'], $sp_config['media_import_op_mode']))
                {
                    continue;
                }
            }
            $temp_op[] = $sp_val['nns_id'];
        }
        $this->op_sp = $temp_op;
        return;
    }

    /**
     * 添加透传队列
     * @params int $type 操作行为类型 0 栏目同步 1 栏目推荐 2 CP同步 3 栏目图片同步 4 媒资融合
     * @param int $action 操作行为 添加修改删除
     * @param string $message_id 消息id
     * @param string $cp_id cp_id
     * @param string $data 透传数据
     * @author zhiyong.luo
     * @date 2017-02-23
     */
    public function q_add_pass_queue_op_mgtv($type, $action, $cp_id, $data, $message_id)
    {
        set_time_limit(0);
        $this->dc = nl_get_dc(array(
            "db_policy" => NL_DB_WRITE,
            "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        //根据CP查询绑定的SP
        $arr_sp = nl_sp::query($this->dc, array('like' => array('nns_bind_cp' => $cp_id)));
        if (!is_array($arr_sp['data_info']) || empty($arr_sp['data_info']))
        {
            return array('ret' => 1, 'reason' => '没有查询到相关cp绑定关系，cp_id为:' . $cp_id);
        }
        $temp_array = array();
        foreach ($arr_sp['data_info'] as $sp_val)
        {
            $sp_config = json_decode($sp_val['nns_config'], true);
            //检查媒资上下线开关是否开启  如果未开启 直接continue
            if (!isset($sp_config['pass_queue_disabled']) || $sp_config['pass_queue_disabled'] != 1)
            {
                $temp_array[] = 'SP为:' . $sp_val . '的透传开关未开启,值为' . $sp_config['pass_queue_disabled'];
                continue;
            }
            //0 为进入透传队列为待审核，1 为审核通过  2审核不通过
            $pass_queue_audit = (isset($sp_config['pass_queue_audit']) && (int)$sp_config['pass_queue_audit'] === 1) ? $sp_config['pass_queue_audit'] : 0;
            list ($usec, $sec) = explode(' ', microtime());
            $time = str_pad(intval(substr($usec, 2, 4)), 4, '0', STR_PAD_LEFT);
            $micro_time = date('YmdHis', time()) . $time;
            $params = array(
                'nns_type' => $type,
                'nns_message_id' => $message_id,
                'nns_org_id' => $sp_val['nns_id'],
                'nns_cp_id' => $cp_id,
                'nns_audit' => $pass_queue_audit,
                'nns_pause' => '0',
                'nns_content' => $data,
                'nns_status' => '1',
                'nns_queue_time' => $micro_time,
                'nns_action' => $action
            );
            $result = nl_pass_queue::add($this->dc, $params);
            if ($result['ret'] != 0)
            {
                return $result;
            }
            unset($params);
            unset($sp_config);
        }
        return array('ret' => 0, 'reason' => '透传队列生成成功', 'data_info' => $temp_array);
    }

    /**
     * 非法字符串替换
     * @param string $string
     * @return string
     * @author liangpan
     * @date 2016-08-27
     */
    public function str_filter($string)
    {
        $array_un_string = array(
            '`', '·', '~', '!', '！', '@', '#', '$', '￥', '%', '^', '……', '&', '*', '(', ')', '（', '）', '-', '_', '——', '+', '=', '|', '\\', '[', ']', '【',
            '】', '{', '}', ';', '；', ':', '：', '\'', '"', '“', '”', ',', '，', '<', '>', '《', '》', '.', '。', '/', '、', '?', '？', ',', ' ', ' '
        );
        return trim(str_replace($array_un_string, '', $string));
    }


    /**
     * 获取影片清晰度名称
     * @param string $code 清晰度标示码
     * @return string 清晰度标示中文描述
     * @author liangpan
     * @date 2016-08-27
     */
    public function get_media_mode($code)
    {
        $code = strtolower(trim($code));
        $return_str = "";
        switch ($code)
        {
            case "std":
                $return_str = "标清";
                break;
            case "hd":
                $return_str = "高清";
                break;
            case "low":
                $return_str = "流畅";
                break;
            case "4k":
                $return_str = "4K";
                break;
            case "sd":
                $return_str = "超高清";
                break;
            default:
                $return_str = $code;
        }
        return $return_str;
    }


    /**
     * 添加审核规则判断那些该注入审核队列
     * @param string $task_name 媒资名称
     * @param string $video_id 主媒资id | 分集id | 片源 id
     * @param string $video_type video 主媒资 | 分集 index | 片源 media
     * @param string $action add 添加 | modify 修改 | destroy 删除
     * @author liangpan
     * @date 2015-09-10
     */
    public function add_vod_audit($task_name, $video_id, $video_type, $action, $nns_kbps = 0, $flag)
    {
        $action = ($action != 'destroy') ? 'add' : $action;
        if (!is_array($this->op_sp) || empty($this->op_sp))
        {
            return;
        }
        $this->dc = nl_get_dc(array(
            "db_policy" => NL_DB_WRITE,
            "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        foreach ($this->op_sp as $key => $val)
        {
            //查询sp配置
            $sp_list_sql = "select * from nns_mgtvbk_sp where nns_id='$val'";
            $sp = nl_db_get_one($sp_list_sql, $this->dc->db());
            $sp_config = json_decode($sp['nns_config'], true);

            //中心注入主令开关，如果关闭了，则排除掉该Sp
            if (isset($sp_config['op_queue_enabled']) && $sp_config['op_queue_enabled'] == '0')
            {
                unset($this->op_sp[$key]);
                continue;
            }

            if ($flag === false)
            {
                $asset_retrieve_config = (strlen(trim($sp_config['asset_retrieve_config'])) > 0) ? trim($sp_config['asset_retrieve_config']) : '';
                $asset_retrieve_config = explode(',', $asset_retrieve_config);
                if (($video_type == 'video' && !in_array(1, $asset_retrieve_config)) || ($video_type == 'index' && !in_array(2, $asset_retrieve_config)) || ($video_type == 'media' && !in_array(3, $asset_retrieve_config)))
                {
                    unset($this->op_sp[$key]);
                    continue;
                }
            }


            //查看码率开关是否开启，开启了处理码率控制逻辑，关闭直接通过
            if ($video_type == 'media' && isset($sp_config['import_ratebit_enabled']) && $sp_config['import_ratebit_enabled'] == '1')
            {
                if (isset($sp_config['import_ratebit_start']) && isset($sp_config['import_ratebit_end']))
                {
                    $ratebit_flag_start = (strlen($sp_config['import_ratebit_start']) < 1 || (strlen($sp_config['import_ratebit_start']) > 0 && $nns_kbps >= $sp_config['import_ratebit_start'])) ? true : false;
                    $ratebit_flag_end = (strlen($sp_config['import_ratebit_end']) < 1 || (strlen($sp_config['import_ratebit_end']) > 0 && $nns_kbps <= $sp_config['import_ratebit_end'])) ? true : false;
                    if (!$ratebit_flag_start || !$ratebit_flag_end)
                    {
                        unset($this->op_sp[$key]);
                        continue;
                    }
                }
            }
            //如果审核队列开启
            if (!isset($sp_config['flow_audit']) || empty($sp_config['flow_audit']))
            {
                continue;
            }


            //上下线控制开关是否开启  false  关闭  |  true  开启
            $online_enable = (!isset($sp_config['flow_unline']) || empty($sp_config['flow_unline'])) ? false : true;
            //取消以前的注入队列
            unset($this->op_sp[$key]);
            //是否自动审核	false 关闭自动注入 | true 开启自动注入
            $audit_flag = (!isset($sp_config['auto_audit_enable']) || empty($sp_config['auto_audit_enable'])) ? false : true;
            //是否敏感词审核   false 不通过敏感词库筛选 |  true 通过敏感词库筛选
            $word_flag = (!isset($sp_config['sensitive_word_enabled']) || empty($sp_config['sensitive_word_enabled'])) ? true : false;
            //如果审核队列只审核  主媒资  分集
            if ((!isset($sp_config['audit_model']) || empty($sp_config['audit_model'])) && ($video_type == 'video' || $video_type == 'index' || $video_type == 'media'))
            {
                //添加媒资审核队列
                $this->add_vod_index_media_audit($task_name, $video_id, $video_type, $val, $action, $audit_flag, $word_flag, $online_enable);
            }
            //如果审核模式  只审核主媒资 分集
            if ($sp_config['audit_model'] == 1 && ($video_type == 'video' || $video_type == 'index'))
            {
                //添加媒资审核队列
                $this->add_vod_index_media_audit($task_name, $video_id, $video_type, $val, $action, $audit_flag, $word_flag, $online_enable);
            } //如果审核模式  只审核主媒资
            else if ($sp_config['audit_model'] == 2 && $video_type == 'video')
            {
                //添加媒资审核队列
                $this->add_vod_index_media_audit($task_name, $video_id, $video_type, $val, $action, $audit_flag, $word_flag, $online_enable);
            }
        }
    }

    /**
     * 添加审核规则
     * @param string $name 名称
     * @param string $nns_id 主媒资id | 分集id | 片源 id
     * @param string $video_type video 主媒资 | 分集 index | 片源 media
     * @param string $sp_id 运营商id
     * @param string $action add 添加 | modify 修改 | destroy 删除
     * @param boolean $audit_flag false 关闭自动注入 | true 开启自动注入
     * @param boolean $word_flag false 不通过敏感词库筛选 |  true 通过敏感词库筛选
     * @author liangpan
     * @date 2015-09-10
     */
    public function add_vod_index_media_audit($name, $nns_id, $video_type, $sp_id, $action, $audit_flag, $word_flag, $online_enable)
    {
        $func = 'query_' . $video_type . '_import_id';
        $result_import_id = nl_vod_index_media::$func($this->dc, $nns_id);
        if ($result_import_id['ret'] != 0 || empty($result_import_id['data']['data_info']))
        {
            return;
        }
        $cp_id = $result_import_id['data']['data_info']['nns_cp_id'];
        $import_id = $result_import_id['data']['data_info']['nns_asset_import_id'];
        //新增的数据进入队列，且现有审核/上下线队列中有一条删除的数据，此条删除的数据并未处理完成，
        //则忽略删除操作的数据和新增的数据不会进入队列。若此条删除的数据已经处理完成，
        //则忽略删除操作的数据切新增的数据进入队列（若之前队列中含有此条数据的新增队列，则初始化此条队列)
        $exsist_vod_audit = nl_vod_audit::query_exsist_vod_audit($this->dc, $import_id, $sp_id, $cp_id);
        if ($exsist_vod_audit['ret'] != 0)
        {
            return;
        }
        $state = 0;
        $check = 0;
        //如果注入表中存在  该数据
        if (is_array($exsist_vod_audit['data']['data_info']) && count($exsist_vod_audit['data']['data_info']) > 1)
        {
            $exsist_vod_audit = $exsist_vod_audit['data']['data_info'][0];
            //如果  方式一样 直接返回
            if ($exsist_vod_audit['nns_action'] == $action)
            {
                return;
            }
            //如果未审核   则 先审核
            if ($exsist_vod_audit['nns_check'] == 0)
            {
                nl_vod_audit_notify_action::push_message_notify($this->dc, $nns_id, 1, $sp_id, 'check', $video_type, $exsist_vod_audit['nns_action'], $exsist_vod_audit['nns_name']);
                //发送消息后 休眠1秒
                @sleep(1);
            }
            if ($online_enable)
            {
                if ($exsist_vod_audit['nns_state'] == 0)
                {
                    //添加  就上线
                    if ($exsist_vod_audit['nns_action'] == 'add')
                    {
                        nl_vod_audit_notify_action::push_message_notify($this->dc, $nns_id, 1, $sp_id, 'line', $video_type, $exsist_vod_audit['nns_action'], $exsist_vod_audit['nns_name']);
                        //发送消息后 休眠1秒
                        @sleep(1);
                    } //删除  就下线
                    else
                    {
                        nl_vod_audit_notify_action::push_message_notify($this->dc, $nns_id, 2, $sp_id, 'line', $video_type, $exsist_vod_audit['nns_action'], $exsist_vod_audit['nns_name']);
                        //发送消息后 休眠1秒
                        @sleep(1);
                    }
                }
            }
        }
        $parent_import_id = null;
        //如果媒资类型不是主媒资 则查询父级注入id
        if ($video_type != 'video')
        {
            $temp_video_type = ($video_type == 'index') ? 'video' : 'index';
            $parent_id = ($video_type == 'index') ? $result_import_id['data']['data_info']['nns_vod_id'] : $result_import_id['data']['data_info']['nns_vod_index_id'];
            $parent_import_id = $this->query_parent_import_id($parent_id, $temp_video_type);
        }
        //没有开启自动注入
        if (!$audit_flag)
        {
            nl_vod_audit::add_vod_audit($this->dc, $name, $import_id, $sp_id, $cp_id, $action, $video_type, $check, $state, $parent_import_id);
            return;
        }
        //开启敏感词审核
        if ($word_flag)
        {
            //验证  是否审核通过
            $check = $this->auto_check_vod($nns_id, $video_type, $sp_id);
            nl_vod_audit::add_vod_audit($this->dc, $name, $import_id, $sp_id, $cp_id, $action, $video_type, $check, $state, $parent_import_id);
            //审核发送消息
            nl_vod_audit_notify_action::push_message_notify($this->dc, $nns_id, $check, $sp_id, 'check', $video_type, $action, $name);
        } //未开启敏感词审核   全部审核
        else
        {
            nl_vod_audit::add_vod_audit($this->dc, $name, $import_id, $sp_id, $cp_id, $action, $video_type, $check, $state, $parent_import_id);
            nl_vod_audit_notify_action::push_message_notify($this->dc, $nns_id, 1, $sp_id, 'check', $video_type, $name);
        }
        return;
    }

    /**
     * 查询分集、片源的父级注入id
     * @param string $parent_id 父级id （分集 id | 片源 id）
     * @param string $video_type video 分集 index | 片源 media
     * @return NULL | string
     * @author liangpan
     * @date 2015-09-10
     */
    public function query_parent_import_id($parent_id, $video_type)
    {
        $result_mix = nl_vod_index_media::query_video_index_media_info($this->dc, $parent_id, $video_type);
        if ($result_mix['ret'] != 0 || !isset($result_mix['data']['data_info'][0]['nns_import_id']) || empty($result_mix['data']['data_info'][0]['nns_import_id']))
        {
            return null;
        }
        return $result_mix['data']['data_info'][0]['nns_import_id'];
    }


    /**
     * 敏感词验证规则
     * @param string $nns_id 主媒资id | 分集id | 片源 id
     * @param string $video_type 主媒资 video | 分集 index | 片源 media
     * @param string $sp_id 运营商id
     * @return number  0 审核未通过 | 1审核通过
     * @author liangpan
     * @date 2015-09-10
     */
    public function auto_check_vod($nns_id, $video_type, $sp_id)
    {
        $check = 2;
        $result_words = nl_vod_audit_word::query_word_list($this->dc, $sp_id);
        //如果没查询到一条铭感词数据   则全部通过
        if ($result_words['ret'] != 0 || empty($result_words['data']['data_info']) || !is_array($result_words['data']['data_info']))
        {
            return 1;
        }
        $result_words = $result_words['data']['data_info'][0]['nns_words'];
        $content = null;
        switch ($video_type)
        {
            case "video":
                //查询主媒资需要匹配的数据
                $result_vod = nl_vod_index_media::query_video_index_media_info($this->dc, $nns_id, $video_type);
                //主媒资扩展信息  先不要
                //$result_vod_ex=nl_vod_index_media::query_video_index_media_ex_info($dc, $import_id,$video_type);
                $result_vod = isset($result_vod['data']['data_info'][0]) ? $result_vod['data']['data_info'][0] : null;
                //没有数据 则审核不通过
                if (empty($result_vod))
                {
                    return $check;
                }
                //nns_remark,nns_play_role,nns_copyright_range,nns_vod_part
                $content = $result_vod['nns_name'] . $result_vod['nns_director'] . $result_vod['nns_actor'] . $result_vod['nns_area'] .
                    $result_vod['nns_summary'] . $result_vod['nns_alias_name'] . $result_vod['nns_eng_name'] . $result_vod['nns_language'] .
                    $result_vod['nns_text_lang'] . $result_vod['nns_producer'] . $result_vod['nns_screenwriter'] . $result_vod['nns_keyword'] .
                    $result_vod['nns_kind'];
                break;
            case "index":
                //检查主媒资是否通过审核  如果未通过审核  直接 分集也未通过审核
                $vod_result = nl_vod_index_media::query_index_media_info_by_id($this->dc, $nns_id, $video_type);
                if ($vod_result['ret'] != 0 || !is_array($vod_result['data']['data_info']) || !isset($vod_result['data']['data_info'][0]['nns_import_id']))
                {
                    return $check;
                }
                $result_audit = nl_vod_audit::query_exsist_vod_audit($this->dc, $vod_result['data']['data_info'][0]['nns_import_id'], $sp_id, $vod_result['data']['data_info'][0]['nns_cp_id']);
                if ($result_audit['ret'] != 0 || !is_array($result_audit['data']['data_info']) || !isset($result_audit['data']['data_info'][0]['nns_check']))
                {
                    return $check;
                }
                if ($result_audit['data']['data_info'][0]['nns_check'] != 1)
                {
                    return $check;
                }
                //查询分集需要匹配的数据
                $result_index = nl_vod_index_media::query_video_index_media_info($this->dc, $nns_id, $video_type);
                //分集扩展信息  先不要
                //$result_index_ex=nl_vod_index_media::query_video_index_media_ex_info($dc, $import_id,$video_type);
                $result_index = isset($result_index['data']['data_info'][0]) ? $result_index['data']['data_info'][0] : null;
                //没有数据 则审核不通过
                if (empty($result_index))
                {
                    return $check;
                }
                $content = $result_index['nns_name'] . $result_index['nns_summary'] . $result_index['nns_actor'] . $result_index['nns_director'] .
                    $result_index['nns_watch_focus'];
                break;
            case "media":
                //检查分集是否通过审核  如果未通过审核  直接 片源也未通过审核
                $vod_result = nl_vod_index_media::query_index_media_info_by_id($this->dc, $nns_id, $video_type);
                if ($vod_result['ret'] != 0 || !is_array($vod_result['data']['data_info']) || !isset($vod_result['data']['data_info'][0]['nns_import_id']))
                {
                    return $check;
                }
                $result_audit = nl_vod_audit::query_exsist_vod_audit($this->dc, $vod_result['data']['data_info'][0]['nns_import_id'], $sp_id, $vod_result['data']['data_info'][0]['nns_cp_id']);
                if ($result_audit['ret'] != 0 || !is_array($result_audit['data']['data_info']) || !isset($result_audit['data']['data_info'][0]['nns_check']))
                {
                    return $check;
                }
                return $result_audit['data']['data_info'][0]['nns_check'];
            default:
                return $check;
        }
        //没有内容 审核也不通过
        if (empty($content))
        {
            return $check;
        }
        if (empty($result_words))
        {
            return 1;
        }
        if (preg_match("/" . $result_words . "/i", $content, $matches))
        {
            return $check;
        } else
        {
            return 1;
        }
    }


    public function get_import_op_list($sp_id, $filter = null, $start = 0, $size = 20)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_READ);

        $sql = "select * from nns_mgtvbk_import_op where nns_op_sp like '%,$sp_id,%'";


        if ($filter != null)
        {
            $wh_arr = array();
            if (!empty($filter['nns_name']))
            {
                $wh_arr[] = " nns_video_name like '%" . $filter['nns_name'] . "%'";
            }
            if (!empty($filter['nns_type']))
            {
                $wh_arr[] = " nns_video_type='" . $filter['nns_type'] . "'";
            }

            if (!empty($filter['day_picker_start']))
            {
                $wh_arr[] = " nns_create_time>='" . $filter['day_picker_start'] . "'";
            }
            if (!empty($filter['day_picker_end']))
            {
                $wh_arr[] = " nns_create_time<='" . $filter['day_picker_end'] . "'";
            }
            if (!empty($filter['nns_action']))
            {
                $wh_arr[] = " nns_action='" . $filter['nns_action'] . "'";
            }
            if (isset($filter['nns_cp_id']) && strlen($filter['nns_cp_id']) > 0)
            {
                $wh_arr[] = " nns_cp_id='" . $filter['nns_cp_id'] . "'";
            }
            if (!empty($wh_arr)) $sql .= " and " . implode(" and ", $wh_arr);
        }

        $count_sql = $sql;
        $count_sql = str_replace('*', ' count(*) as temp_count ', $count_sql);
        $sql .= " order by nns_weight desc,nns_op_mtime asc ";
        $sql .= " limit $start,$size";
        $data = nl_db_get_all($sql, $db);
        $rows = nl_db_get_col($count_sql, $db);
        return array('data' => $data, 'rows' => $rows);

    }

    /**
     * 获得主媒资上下线列表
     *
     * @param string $sp_id 运营商ID
     * @param string $filter
     * @param int $start
     * @param int $size
     */
    public function get_import_asset_online_list($sp_id)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_READ);
        $sql = "(select * from nns_import_asset_online where nns_org_id = '{$sp_id}' and nns_audit='1'  " .
            " and nns_delete='0' and nns_status ='1' and nns_fail_time <= 100 order by nns_create_time asc limit 60) union " .
            "(select * from nns_import_asset_online where nns_org_id = '{$sp_id}' and nns_audit='1'  " .
            " and nns_delete='0' and nns_status ='2' and nns_fail_time <= 100 order by nns_modify_time asc limit 20) union " .
            "(select * from nns_import_asset_online where nns_org_id = '{$sp_id}' and nns_audit='1'  " .
            " and nns_delete='0' and nns_status in('4','5','6','7') and nns_fail_time <= 100 order by nns_modify_time asc limit 20)";
        return nl_db_get_all($sql, $db);
    }

    /**
     * 获得主媒资上下线列表
     *
     * @param string $sp_id 运营商ID
     * @param string $filter
     * @param int $start
     * @param int $size
     */
    public function set_delete_asset_online()
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $sql = "update nns_import_asset_online set nns_delete='1' where nns_fail_time > 100";
        return nl_execute_by_db($sql, $db);
    }

    /**
     * 更新处理过的下发消息的状态
     * @param string $nns_id 记录主键ID
     * @param bool $is_success 是否推送成功
     */
    public function update_asset_online_record($nns_id, $is_success = true)
    {
        set_time_limit(0);
        $now = date('Y-m-d H:i:s');
        $db = nn_get_db(NL_DB_WRITE);
        if ($is_success)
        {
            $sql = "UPDATE nns_mgtvbk_message SET nns_message_state = 3,nns_modify_time='$now' WHERE nns_id = '$nns_id'";
        } else
        {
            $mtime = explode(' ', microtime());
            $fail_time = $mtime[1] . substr($mtime[0], 2);
            $sql = "UPDATE nns_mgtvbk_message SET nns_message_state = 4,nns_modify_time='$now',nns_fail_time='$fail_time',nns_again=nns_again+1 WHERE nns_id = '$nns_id'";
        }
        nl_query_by_db($sql, $db);
    }

    public function add_task_to_queue($sp_id, $nns_id)
    {
        set_time_limit(0);
        $dc = nl_get_dc(array(
            "db_policy" => NL_DB_WRITE,
            "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
        ));
// 		$db = nn_get_db(NL_DB_WRITE);
        $db = $dc->db();
        $sql = "select * from nns_mgtvbk_import_op where nns_id='$nns_id'";
        $data = nl_db_get_one($sql, $db);

        $sp_list_sql = "select * from nns_mgtvbk_sp where nns_id='$sp_id'";
        $sp = nl_db_get_one($sp_list_sql, $db);
        if (is_array($data))
        {
            $sp_config = json_decode($sp['nns_config'], true);
            //如果是片源  且需要切片下载
            if (isset($sp_config['cdn_import_media_mode']) && ((int)$sp_config['cdn_import_media_mode'] === 1 || (int)$sp_config['cdn_import_media_mode'] === 2) && $data['nns_video_type'] == BK_OP_MEDIA)
            {
                $current = nl_db_get_one("select * from nns_vod_media where nns_id='{$data['nns_video_id']}'", $db);
                $sql = "select * from nns_vod_media where nns_vod_index_id='{$current['nns_vod_index_id']}' and nns_deleted!=1 and nns_media_service='{$current['nns_media_service']}' order by nns_kbps desc limit 1";
                $new_media_info = nl_db_get_one($sql, $db);

                $result_cp = nl_cp::query_by_id($dc, $new_media_info['nns_cp_id']);
                $result_cp_config = (isset($result_cp['data_info']['nns_config']) && strlen($result_cp['data_info']['nns_config']) > 0) ? json_decode($result_cp['data_info']['nns_config'], true) : null;

                if ($data['nns_action'] == 'add' || $data['nns_action'] == 'modify')
                {
                    if ($new_media_info['nns_id'] == $data['nns_video_id'])
                    {
                        $bool = $this->q_add_task($data['nns_video_id'], $data['nns_video_type'], $data['nns_action'], $sp_id, null, false, $data['nns_message_id'], null, $data['nns_weight'], $data['nns_is_group'], $sp_config);
                    } else
                    {
                        $bool = $this->q_add_task($new_media_info['nns_id'], $data['nns_video_type'], $data['nns_action'], $sp_id, $data['nns_video_id'], FALSE, $data['nns_message_id'], null, $data['nns_weight'], 0, $sp_config);
                    }
                } else if ($data['nns_action'] == 'destroy')
                {
                    if (is_array($new_media_info))
                    {
                        $bool = $this->q_add_task($new_media_info['nns_id'], $data['nns_video_type'], $data['nns_action'], $sp_id, $data['nns_video_id'], FALSE, $data['nns_message_id'], null, $data['nns_weight'], 0, $sp_config);
                    } else
                    {
                        $bool = $this->q_add_task($data['nns_video_id'], $data['nns_video_type'], $data['nns_action'], $sp_id, $data['nns_video_id'], FALSE, $data['nns_message_id'], null, $data['nns_weight'], $data['nns_is_group'], $sp_config);
                    }
                }
            } //如果是主媒资或者分集，或者和片源不需要切片下载
            else
            {
                $bool = $this->q_add_task($data['nns_video_id'], $data['nns_video_type'], $data['nns_action'], $sp_id, null, FALSE, $data['nns_message_id'], null, $data['nns_weight'], $data['nns_is_group'], $sp_config);
            }
// 			$bool_1 = true;
// 			if(isset($sp_config['audit_audit']) && !empty($sp_config['audit_audit']))
// 			{
// 				$bool_1 = $this->check_pass_audit($data['nns_video_type'],$data['nns_video_id'],$sp_id);
// 			}
//			if($bool && $bool_1)
            if ($bool)
            {
                $data['nns_op_sp'] = trim($data['nns_op_sp'], ',');
                $nns_op_sp = explode(',', $data['nns_op_sp']);
                $arr = array_flip($nns_op_sp);
                unset($arr[$sp_id]);
                $arr = array_flip($arr);
                if (empty($arr) || !is_array($arr))
                {
                    $ex_sql = "delete from nns_mgtvbk_import_op where nns_id='$nns_id'";
                } else
                {
                    $sp = ',' . implode(',', $arr) . ",";
                    $ex_sql = "update  nns_mgtvbk_import_op  set nns_op_sp='$sp' where nns_id='$nns_id'";
                }
                nl_execute_by_db($ex_sql, $db);
            }
        }
    }

    /**
     * 验证审核是否通过   （已弃用）
     * @param unknown $video_type
     * @param unknown $nns_id
     * @param unknown $sp_id
     * @return boolean
     */
    public function check_pass_audit($video_type, $nns_id, $sp_id)
    {
        $dc = nl_get_dc(array(
            "db_policy" => NL_DB_WRITE,
            "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $bool = false;
        switch ($video_type)
        {
            case "video":
                $result_import_id = nl_vod_audit::check_video_is_continue_by_id($dc, $org_id, $nns_id);
                break;
            case "index":
                $result_import_id = nl_vod_audit::check_index_is_continue_by_id($dc, $org_id, $nns_id);
                break;
            case "media":
                $result_import_id = nl_vod_audit::check_media_is_continue_by_id($dc, $org_id, $nns_id);
                break;
            default:
                return $bool;
        }
        if ($result_import_id['ret'] == 0)
        {
            if (is_array($result_import_id['data']['data_info']))
            {
                $result_import_id = $result_import_id['data']['data_info'][0];
                if ($result_import_id['nns_check'] == '1')
                {
                    $bool = true;
                }
            }
        }
        unset($result_import_id);
        return $bool;
    }
    /***********************20150302**************************/
    /**
     * 手动获取切片任务
     * @param $sp_id spID
     * @param $op_ids 中心同步指令ID array();
     * @author zhiyong.luo
     * @date 2015-03-02
     */

    public function q_hand_get_clip_task($sp_id, $op_ids)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $re = $this->op_queue->get_hand_clip($db, $sp_id, $op_ids);
        //print_r($re);die;

        //从操作列队中获取的任务添加到切片任务表中，由切片程序获取任务使用
        if ($re['state'] == 100 && is_array($re['data']) && !empty($re['data']))
        {
            foreach ($re['data'] as $q_clip_task_info)
            {
                //添加切片任务
                $clip_params = array(
                    'nns_video_type' => 0,
                    'nns_video_id' => $q_clip_task_info['nns_video_id'],
                    'nns_video_index_id' => $q_clip_task_info['nns_index_id'],
                    'nns_video_media_id' => $q_clip_task_info['nns_media_id'],
                    'nns_task_name' => $q_clip_task_info['nns_name'],
                    'nns_op_id' => $q_clip_task_info['nns_id'],
                    'nns_org_id' => $sp_id,
                    'nns_cp_id' => $q_clip_task_info['nns_cp_id'],
                );
                $clip_result = clip_task_model::add_task($clip_params);
                //var_dump($clip_result);
                if ($clip_result === true)
                {
                    $this->op_queue->clip_progress($db, $q_clip_task_info['nns_id']);
                }
            }
        }
    }

    /**
     * 栏目绑定黑白名单
     * nns_type为2，指栏目
     * $params = array('nns_id'=>'资源库Id',nns_type='名单类型','nns_is_black'=>1/0);
     * 黑名单：1
     * 白名单：0
     * @author zhiyong.luo
     * @date 2015-03-03
     */

    public function add_category_blacklist($sp_id, $params)
    {
        set_time_limit(0);
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $sql = "select * from nns_mgtvbk_op_blacklist where nns_org_id='" . $sp_id .
            "' and nns_type='{$params['nns_type']}' and nns_category_id='{$params['nns_category_id']}'";

        $info = nl_db_get_one($sql, $db);
        //若有数据，则修改
        if (is_array($info) && !empty($info))
        {
            $str_sql = "update nns_mgtvbk_op_blacklist set nns_is_black='{$params['nns_is_black']}',
					nns_name='{$params['nns_name']}' where nns_category_id='{$params['nns_category_id']}' 
					and nns_org_id='{$sp_id}' and nns_type='{$params['nns_type']}' and nns_id='{$info['nns_id']}'";
            $re = nl_execute_by_db($str_sql, $db);
            if ($re)
            {
                return array('data' => 0, 'id' => $info['nns_id']);
            } else
            {
                return array('data' => 1);
            }
        }
        $data = array(
            'nns_id' => np_guid_rand(),
            'nns_name' => $params['nns_name'],
            'nns_category_id' => $params['nns_category_id'],
            'nns_type' => $params['nns_type'],
            'nns_org_id' => $sp_id,
            'nns_create_time' => date('Y-m-d H:i:s'),
            'nns_is_black' => $params['nns_is_black']
        );
        $result = nl_db_insert($db, 'nns_mgtvbk_op_blacklist', $data);
        if ($result === true)
        {
            return array('data' => 0, 'id' => $data['nns_id']);
        } else
        {
            return array('data' => 1);
        }
    }

    /**
     * 根据视频id获取栏目ID
     */
    public function get_category_by_video_id($db, $video_id)
    {
        $sql = "select nns_category_id from nns_vod where nns_id='{$video_id}'";
        $re = nl_query_by_db($sql, $db);
        if (!is_array($re))
        {
            return null;
        }
        return $re[0]['nns_category_id'];
    }

    /**
     * 获取消息队列列表
     * @param array $params = array(
     *        'nns_id'            => 记录ID,
     *        'nns_message_id'    => 消息ID,
     *        'nns_name'            => 名称,
     *        'nns_message_state'    => 状态,
     *        'nns_type'            => 媒资类型,
     *        'nns_action'        => 操作类型
     * )
     * @param number $start 分页开始
     * @param number $sise 每页条数
     * @return array('data' => 数据, 'rows' => 总条数)
     * @author chunyang.shu
     * @date 2015-03-23
     */
    public function get_cp_message_list($params = array(), $start = 0, $size = 12,$bk_version_number=false)
    {
        $linux_mysql_flag = false;
        $db = nn_get_db(NL_DB_READ);
        $str_sql = "select * from nns_mgtvbk_message ";
        $where = '';
        if (is_array($params) && count($params) > 0)
        {
            foreach ($params as $key => $value)
            {
                if (strlen($value) > 0)
                {
                    if ($key == 'nns_name')
                    {
                        $where .= " and {$key} like '%{$value}%' ";
                    } else if ($key == 'date_begin')
                    {
                        $time = date('Y-m-d H:i:s', strtotime($value));
                        $where .= " and nns_create_time >= '{$time}' ";
                    } else if ($key == 'date_end')
                    {
                        $time = date('Y-m-d H:i:s', strtotime($value));
                        $where .= " and nns_create_time <= '{$time}' ";
                    } else if ($key == 'date_begin_modify')
                    {
                        $time = date('Y-m-d H:i:s', strtotime($value));
                        $where .= " and nns_modify_time >= '{$time}' ";
                    } else if ($key == 'date_end_modify')
                    {
                        $time = date('Y-m-d H:i:s', strtotime($value));
                        $where .= " and nns_modify_time <= '{$time}' ";
                    } else if ($key == 'nns_content')
                    {
                        $linux_mysql_flag = true;
                        if($bk_version_number)
                        {
                            $linux_mysql_data = m_linux_mysql_query::linux_mysql_exchange('message','content',$value,isset($params['nns_cp_id']) ? $params['nns_cp_id'] : '');
                            //$where .= m_linux_mysql_query::make_sql('nns_message_url',$linux_mysql_data['data_info'] ,$start/$size,$size);
                            $str_where = m_linux_mysql_query::make_sql('nns_id',$linux_mysql_data['data_info'] ,$start/$size,$size,false);
                            if(!empty($str_where))
                            {
                                $where .= $str_where;
                            }
                            else
                            {
                                $where .= " and 1!=1 ";
                            }
                        }
                        else
                        {
                            $where .= " and nns_message_content like '%{$value}%' ";
                        }
                    } else if ($key == 'nns_again')
                    {
                        $where .= " and nns_again >='{$value}' ";
                    } else
                    {
                        $where .= " and {$key}='{$value}' ";
                    }
                }
            }
        }
        //-->start xingcheng.hu 去掉where 1=1
        if (!empty($where))
        {
            $str_sql .= 'where';
            $where = ltrim($where, ' ');
            $where = ltrim($where, 'and');
            $str_sql .= $where;
        }
        //<--end
        $count_sql = str_replace(" * ", " count(1) as count ", $str_sql);

        $str_sql .= " order by nns_create_time desc,nns_message_time desc";
        if($linux_mysql_flag && $bk_version_number)
        {
            $str_sql .= " limit 0,{$size}";
            $rows = count($linux_mysql_data['data_info']);
        }
        else
        {
            $str_sql .= " limit {$start},{$size}";
            $rows = nl_db_get_col($count_sql, $db);
        }
        $data = nl_db_get_all($str_sql, $db);
        return array('data' => $data, 'rows' => $rows);
    }

    /**
     * 重庆有线存量注入队列
     * @param $sp_id
     * @param $media_id
     * @param $index_id
     * @param $vod_id
     * @author xingcheng.hu
     * @date 2016-10-26
     */
    public function cqyx_stock_import($sp_id, $media_id, $index_id, $vod_id)
    {
        if (empty($sp_id) || empty($media_id) || empty($index_id) || empty($vod_id))
        {
            return;
        }
        $db = nn_get_db(NL_DB_WRITE);
        $db->open();
        $sql_video = "select nns_id from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='video' and nns_ref_id='{$vod_id}'";
        $video_info = nl_db_get_one($sql_video, $db);
        //判断如果不存在才注入
        if (empty($video_info))
        {
            $this->q_add_task($vod_id, BK_OP_VIDEO, BK_OP_ADD, $sp_id, null, true);
        }
        unset($sql_video, $video_info);
        $sql_index = "select nns_id from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='index' and nns_ref_id='{$index_id}'";
        $index_info = nl_db_get_one($sql_index, $db);
        //判断如果不存在才注入
        if (empty($index_info))
        {
            $this->q_add_task($index_id, BK_OP_INDEX, BK_OP_ADD, $sp_id, null, true);
        }
        unset($sql_index, $index_info);
        $sql_media = "select nns_id from nns_mgtvbk_c2_task where nns_org_id='$sp_id' and nns_type='media' and nns_ref_id='{$media_id}'";
        $media_info = nl_db_get_one($sql_video, $db);
        //判断如果不存在才注入
        if (empty($media_info))
        {
            $this->q_add_task($media_id, BK_OP_MEDIA, BK_OP_ADD, $sp_id, null, true);
        }
        unset($sql_media, $media_info);
    }

    /**
     * 外部调用取消子级注入任务
     * @param $sp_id
     * @param $type
     * @param $video_id
     * @author xingcheng.hu
     */
    public function set_child_task_cancel($sp_id, $type, $video_id)
    {
        $this->__set_child_cancel($sp_id, $type, $video_id);
    }


    /**
     * 联通集约化测试 D3接口消息反馈上游
     *   说明：专门用于反馈单个下载失败的任务
     * @author feijian.gao
     * @date   2017年4月9日13:36:29
     *
     * @param  array $task_op_queue 此任务的op_queue队列的信息
     * @return void
     */
    public function unicom_d3_return_download_fail($task_op_queue)
    {
        $db = nn_get_db(NL_DB_READ);
        $db->open();

        if ($task_op_queue["nns_is_group"] == 1)
            $this->op_queue->edit_message_group_info($task_op_queue, array('ret' => 1, 'reason' => 'down fail'));
        else
        {
            $sql = "select * from nns_mgtvbk_message where nns_message_id = '{$task_op_queue['nns_message_id']}'";
            $arr_message_info = nl_db_get_one($sql, $db);
            $db->close();
            $data = simplexml_load_string($arr_message_info["nns_message_content"]);
            $result = json_decode(json_encode($data), true);
            $cdn_id = $result["CDNID"];
            $task_id = $result["Tasklist"]["Task"]["@attributes"]["TaskID"];
            $task_number = $result["Tasklist"]["TaskNum"];
            $str_feedback_address = $result["ResponseURL"];
            $feedback_xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<PrefetchStatus>
  <CDNID>{$cdn_id}</CDNID>
  <Tasklist>
    <TaskNum>{$task_number}</TaskNum>
    <Task TaskID="{$task_id}" Status="-1"/>
  </Tasklist>
</PrefetchStatus>
XML;
            //若已经上报则直接返回
            if (!$this->d3_response_xml($feedback_xml, $task_op_queue['nns_message_id']))
                return;
            //没有上报，继续上报
            $obj_curl = curl_init();
            curl_setopt($obj_curl, CURLOPT_URL, $str_feedback_address);
            curl_setopt($obj_curl, CURLOPT_POST, true);
            curl_setopt($obj_curl, CURLOPT_POSTFIELDS, $feedback_xml);
            curl_setopt($obj_curl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
            $result_notify = curl_exec($obj_curl);
            $http_code = curl_getinfo($obj_curl);
        }
    }

    /**
     * 将上报内容生成文件，保证上报一次
     * @param string $xml_content xml内容
     * @param string $message_id 消息ID
     * @return bool|int 返回 TRUE或者FALSE  TRUE表示需要上报，FALSE表示不用上报
     */
    public function d3_response_xml($xml_content, $message_id)
    {
        $date_file = date("Ymd", time());
        $str_d3_log_dir = dirname(dirname(dirname(__FILE__)));
        $str_xml_response_file = $str_d3_log_dir . "/data/d3_log/d3_response_info/{$date_file}/";
        $str_file_name = $message_id . '.xml';
        if (!is_dir($str_xml_response_file))
        {
            @mkdir($str_xml_response_file, 777, true);
            @chmod($date_file, 777);
        }

        if (is_file($str_xml_response_file . $str_file_name))
        {
            return false;
        } else
        {
            $flag = file_put_contents($str_xml_response_file . $str_file_name, $xml_content);
            return $flag;
        }
    }

    /**
     * 取消C2注入任务,包含当前层级
     * @param $db DB
     * @param $c2_id C2TASK的ID
     * @return boolean
     * @date 2017-05-18
     * @author zhiyong.luo
     */
    public function cancel_c2_task($db, $c2_id)
    {
        if (empty($c2_id))
        {
            return false;
        }
        $sql = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_id}' and nns_status not in ('5','6','7','8') and nns_epg_status != '100'";
        $info = nl_db_get_one($sql, $db);//不能取消正在注入等待CDN反馈以及已经取消的任务
        if (empty($info))
        {
            return false;
        }
        if ($info['nns_type'] !== BK_OP_MEDIA)
        {
            $this->__set_child_cancel($info['nns_org_id'], $info['nns_type'], $info['nns_ref_id']);
        }
        //取消当前层级任务
        $op_id = $info['nns_op_id'];
        $this->op_queue->task_cancel($db, $op_id);
        return nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_id='{$c2_id}'", $db);
    }

    /**
     * 删除中心注入指令
     * @param $sp_id SPID
     * @param $nns_id 中心队列GUID
     */
    public function delete_import_op($sp_id, $nns_id)
    {
        $dc = nl_get_dc(array(
            "db_policy" => NL_DB_WRITE,
            "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $db = $dc->db();
        $sql = "select * from nns_mgtvbk_import_op where nns_id='$nns_id'";
        $data = nl_db_get_one($sql, $db);

        $data['nns_op_sp'] = trim($data['nns_op_sp'], ',');
        $nns_op_sp = explode(',', $data['nns_op_sp']);
        $arr = array_flip($nns_op_sp);
        unset($arr[$sp_id]);
        $arr = array_flip($arr);
        if (empty($arr) || !is_array($arr))
        {
            $ex_sql = "delete from nns_mgtvbk_import_op where nns_id='$nns_id'";
        } else
        {
            $sp = ',' . implode(',', $arr) . ",";
            $ex_sql = "update nns_mgtvbk_import_op  set nns_op_sp='$sp' where nns_id='$nns_id'";
        }
        nl_execute_by_db($ex_sql, $db);
    }
}
